Complete the code to create a new thread in Ruby.
thread = Thread.[1] do puts 'Hello from thread' end thread.join
In Ruby, Thread.new is used to create a new thread.
Complete the code to safely increment a shared counter using a Mutex.
mutex = Mutex.new counter = 0 mutex.[1] do counter += 1 end
The synchronize method locks the mutex, runs the block, then unlocks it.
Fix the error in the code to avoid race conditions when updating the shared variable.
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
You must use a Mutex object to synchronize access to shared data.
Fill both blanks to create a thread-safe hash using a Mutex.
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)Use synchronize to lock the mutex and :key as a symbol key for the hash.
Fill all three blanks to safely update a shared array in multiple threads.
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]
Use synchronize to lock the mutex, push to add elements, and sort to display sorted results.
