Bird
0
0

Identify the issue in this Ruby code related to thread safety and suggest a fix:

medium📝 Debug Q7 of 15
Ruby - Concurrent Programming

Identify the issue in this Ruby code related to thread safety and suggest a fix:

mutex = Mutex.new
counter = 0
threads = 3.times.map do
  Thread.new do
    100.times do
      counter += 1
    end
  end
end
threads.each(&:join)
puts counter
AThe threads array is not joined properly; use threads.each(&:wait)
BThe counter increment is not synchronized; wrap it with mutex.synchronize { counter += 1 }
CMutex is unnecessary because GIL prevents race conditions
DUse Thread.fork instead of Thread.new for better safety
Step-by-Step Solution
Solution:
  1. Step 1: Identify thread safety issue

    Incrementing counter is not atomic and can cause race conditions.
  2. Step 2: Use mutex to synchronize

    Wrap counter increment inside mutex.synchronize block to ensure atomicity.
  3. Final Answer:

    The counter increment is not synchronized; wrap it with mutex.synchronize { counter += 1 } -> Option B
  4. Quick Check:

    Mutex ensures safe access to shared data [OK]
Quick Trick: Use mutex.synchronize to protect shared variable increments [OK]
Common Mistakes:
  • Assuming GIL prevents all race conditions
  • Using incorrect thread join method
  • Believing Thread.fork improves thread safety

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes