Bird
0
0

Identify the problem in this Ruby code that uses threads:

medium📝 Debug Q14 of 15
Ruby - Concurrent Programming
Identify the problem in this Ruby code that uses threads:
counter = 0
threads = 3.times.map do
  Thread.new do
    100.times { counter += 1 }
  end
end
threads.each(&:join)
puts counter
AThread.new syntax is incorrect
BThreads are not joined, so program ends early
CNo Mutex used, so race condition may cause wrong counter value
DCounter variable is not initialized
Step-by-Step Solution
Solution:
  1. Step 1: Check thread safety of counter increment

    Multiple threads increment counter without synchronization, causing race conditions.
  2. Step 2: Identify missing Mutex usage

    Without Mutex, increments can overlap and produce incorrect final value.
  3. Final Answer:

    No Mutex used, so race condition may cause wrong counter value -> Option C
  4. Quick Check:

    Missing Mutex causes race condition [OK]
Quick Trick: Always use Mutex to protect shared variables [OK]
Common Mistakes:
  • Thinking threads are not joined (they are)
  • Assuming counter needs initialization (it is initialized)
  • Believing Thread.new syntax is wrong

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes