Bird
0
0

Identify the problem in this Ruby code using threads and fix it:

medium📝 Debug Q14 of 15
Ruby - Concurrent Programming

Identify the problem in this Ruby code using threads and fix it:

count = 0
threads = 3.times.map do
  Thread.new do
    100.times { count += 1 }
  end
end
threads.each(&:join)
puts count
AAdd a Mutex to synchronize increments
BRemove threads and run increments sequentially
CUse Thread.kill to stop threads early
DNo problem, code is correct
Step-by-Step Solution
Solution:
  1. Step 1: Identify race condition on count variable

    Multiple threads increment count without synchronization causing race conditions.
  2. Final Answer:

    Add a Mutex to synchronize increments -> Option A
  3. Quick Check:

    Mutex prevents race conditions [OK]
Quick Trick: Use Mutex to protect shared data in threads [OK]
Common Mistakes:
  • Ignoring race conditions on shared variables
  • Trying to kill threads instead of synchronizing
  • Assuming GIL handles all thread safety

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes