Bird
0
0

You want to safely update a shared hash from multiple threads in Ruby. Which approach correctly uses Mutex to avoid race conditions?

hard📝 Application Q15 of 15
Ruby - Concurrent Programming
You want to safely update a shared hash from multiple threads in Ruby. Which approach correctly uses Mutex to avoid race conditions?
shared_hash = {}
mutex = Mutex.new
threads = 5.times.map do |i|
  Thread.new do
    10.times do |j|
      # What goes here?
    end
  end
end
threads.each(&:join)
puts shared_hash.size
Amutex.synchronize { shared_hash[i * 10 + j] = "value" }
Bshared_hash[i * 10 + j] = "value"
Cmutex.lock; shared_hash[i * 10 + j] = "value";
DThread.pass; shared_hash[i * 10 + j] = "value"
Step-by-Step Solution
Solution:
  1. Step 1: Understand thread safety for shared hash

    Multiple threads writing to shared_hash need protection to avoid data corruption.
  2. Step 2: Use mutex.synchronize for safe updates

    mutex.synchronize { shared_hash[i * 10 + j] = "value" } wraps the update inside mutex.synchronize, ensuring only one thread writes at a time.
  3. Final Answer:

    mutex.synchronize { shared_hash[i * 10 + j] = "value" } -> Option A
  4. Quick Check:

    Use synchronize block to protect shared hash updates [OK]
Quick Trick: Wrap shared data updates inside mutex.synchronize { } [OK]
Common Mistakes:
  • Updating shared hash without mutex
  • Locking mutex without unlocking
  • Using Thread.pass instead of mutex

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes