Bird
0
0

What will this Ruby code output?

medium📝 Predict Output Q5 of 15
Ruby - Concurrent Programming
What will this Ruby code output?
count = 0
threads = 2.times.map do
  Thread.new do
    5.times { count += 1 }
  end
end
threads.each(&:join)
puts count
A10
B5
CMay vary between 5 and 10
D0
Step-by-Step Solution
Solution:
  1. Step 1: Analyze shared variable access

    Two threads increment count 5 times each, but no lock means race conditions.
  2. Step 2: Understand race condition effect

    Count may not reach 10 because increments can overlap and overwrite each other.
  3. Final Answer:

    May vary between 5 and 10 -> Option C
  4. Quick Check:

    Race condition causes variable count to vary [OK]
Quick Trick: Shared variables need locks to avoid race conditions [OK]
Common Mistakes:
  • Assuming count always equals 10
  • Ignoring race conditions in threads
  • Expecting count to stay 0

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes