Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new thread in Ruby.
Ruby
thread = Thread.[1] do puts 'Hello from thread' end thread.join
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'start' instead of 'new' to create a thread.
Using 'create' or 'run' which are not valid Thread methods.
✗ Incorrect
In Ruby, Thread.new is used to create a new thread.
2fill in blank
mediumComplete the code to safely increment a shared counter using a Mutex.
Ruby
mutex = Mutex.new counter = 0 mutex.[1] do counter += 1 end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'lock' without unlocking the mutex.
Using 'acquire' or 'wait' which are not Ruby Mutex methods.
✗ Incorrect
The synchronize method locks the mutex, runs the block, then unlocks it.
3fill in blank
hardFix the error in the code to avoid race conditions when updating the shared variable.
Ruby
mutex = Mutex.new count = 0 threads = [] 5.times do threads << Thread.new do [1].synchronize do count += 1 end end end threads.each(&:join) puts count
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to synchronize on the shared variable itself.
Using Thread or self which do not provide locking.
✗ Incorrect
You must use a Mutex object to synchronize access to shared data.
4fill in blank
hardFill both blanks to create a thread-safe hash using a Mutex.
Ruby
mutex = Mutex.new
safe_hash = {}
threads = 3.times.map do
Thread.new do
mutex.[1] do
safe_hash[[2]] = 'value'
end
end
end
threads.each(&:join) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'lock' instead of 'synchronize' for mutex.
Using a variable 'key' without defining it.
✗ Incorrect
Use synchronize to lock the mutex and :key as a symbol key for the hash.
5fill in blank
hardFill all three blanks to safely update a shared array in multiple threads.
Ruby
mutex = Mutex.new shared_array = [] threads = [] 5.times do |i| threads << Thread.new do mutex.[1] do shared_array.[2](i) end end end threads.each(&:join) puts shared_array.[3]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'lock' instead of 'synchronize' for mutex.
Using 'append' instead of 'push' for arrays.
Not sorting the array before printing.
✗ Incorrect
Use synchronize to lock the mutex, push to add elements, and sort to display sorted results.