Consider the following Ruby code that uses a Mutex to synchronize threads incrementing a shared counter.
require 'thread'
counter = 0
mutex = Mutex.new
threads = []
10.times do
threads << Thread.new do
100.times do
mutex.synchronize do
counter += 1
end
end
end
end
threads.each(&:join)
puts counterWhat will be printed?
require 'thread' counter = 0 mutex = Mutex.new threads = [] 10.times do threads << Thread.new do 100.times do mutex.synchronize do counter += 1 end end end end threads.each(&:join) puts counter
Think about what the Mutex does to the shared variable.
The Mutex ensures only one thread at a time can increment the counter. Since 10 threads each increment 100 times, the final count is 1000.
Look at this Ruby code where multiple threads increment a shared variable without a Mutex:
counter = 0
threads = []
10.times do
threads << Thread.new do
100.times do
counter += 1
end
end
end
threads.each(&:join)
puts counterWhat is the most likely output?
counter = 0 threads = [] 10.times do threads << Thread.new do 100.times do counter += 1 end end end threads.each(&:join) puts counter
Think about what happens when multiple threads change the same variable without protection.
Without a Mutex, threads can interfere with each other causing some increments to be lost. So the final count is usually less than 1000.
Find the error in this Ruby code snippet that tries to use a Mutex to protect a shared resource:
mutex = Mutex.new counter = 0 Thread.new do mutex.lock counter += 1 end mutex.unlock puts counter
mutex = Mutex.new counter = 0 Thread.new do mutex.lock counter += 1 end mutex.unlock puts counter
Think about which thread owns the lock when unlocking.
Only the thread that locked the mutex can unlock it. Unlocking from the main thread causes a ThreadError.
Choose the Ruby code snippet that correctly uses a Mutex to safely append to a shared array from multiple threads.
Look for proper use of synchronize and thread joining.
Option A correctly uses mutex.synchronize inside each thread and waits for all threads to finish before printing the array size.
Consider this Ruby code that uses a Mutex to safely add keys to a shared hash from multiple threads:
require 'thread'
shared_hash = {}
mutex = Mutex.new
threads = []
5.times do |i|
threads << Thread.new do
10.times do |j|
mutex.synchronize do
shared_hash["key_#{i}_#{j}"] = i * j
end
end
end
end
threads.each(&:join)
puts shared_hash.sizeWhat will be printed?
require 'thread' shared_hash = {} mutex = Mutex.new threads = [] 5.times do |i| threads << Thread.new do 10.times do |j| mutex.synchronize do shared_hash["key_#{i}_#{j}"] = i * j end end end end threads.each(&:join) puts shared_hash.size
Count how many unique keys are added by all threads combined.
There are 5 threads, each adding 10 unique keys. So total keys = 5 * 10 = 50.