Bird
0
0

What will be the output of this Ruby code considering the GIL?

medium📝 Predict Output Q13 of 15
Ruby - Concurrent Programming

What will be the output of this Ruby code considering the GIL?

count = 0
threads = 5.times.map do
  Thread.new do
    1000.times { count += 1 }
  end
end
threads.each(&:join)
puts count
A5000
B1000
CMay be less than 5000 due to race conditions
D0
Step-by-Step Solution
Solution:
  1. Step 1: Understand thread increments with GIL

    GIL allows one thread at a time, but count += 1 is not atomic and can cause race conditions.
  2. Final Answer:

    May be less than 5000 due to race conditions -> Option C
  3. Quick Check:

    Non-atomic increments + threads = race condition [OK]
Quick Trick: GIL doesn't prevent race conditions on shared data [OK]
Common Mistakes:
  • Assuming GIL makes increments atomic
  • Expecting exact 5000 without synchronization
  • Ignoring thread interference on variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes