Complete the code to create a new Mutex object.
mutex = [1].newThe Mutex.new creates a new mutex object used for thread synchronization.
Complete the code to lock the mutex before accessing the shared resource.
mutex.[1] do # critical section end
The synchronize method locks the mutex, runs the block, then unlocks it automatically.
Fix the error in the code to properly unlock the mutex after locking it.
mutex.lock # critical section mutex.[1]
After calling lock, you must call unlock to release the mutex.
Fill both blanks to create a thread-safe increment of a shared counter.
counter = 0 mutex = Mutex.new thread = Thread.new do mutex.[1] do counter [2] 1 end end thread.join
Use synchronize to lock the mutex during increment, and += to add 1 to the counter.
Fill all three blanks to create two threads that safely increment a shared variable.
counter = 0 mutex = Mutex.new threads = [] 2.times do threads << Thread.new do mutex.[1] do temp = counter temp [2] 1 counter = temp end end end threads.each(&:[3])
Use synchronize to lock the mutex, += to increment, and join to wait for threads to finish.
