Bird
0
0

Given this Ruby code, what is the expected output considering the GIL?

medium📝 Predict Output Q5 of 15
Ruby - Concurrent Programming

Given this Ruby code, what is the expected output considering the GIL?

require 'thread'
mutex = Mutex.new
count = 0
threads = []
5.times do
  threads << Thread.new do
    1000.times do
      mutex.synchronize { count += 1 }
    end
  end
end
threads.each(&:join)
puts count
ALess than 5000 due to race conditions
BAn error because Mutex is not used correctly
C0
D5000
Step-by-Step Solution
Solution:
  1. Step 1: Identify mutex usage

    The code uses a Mutex to synchronize increments, preventing race conditions.
  2. Step 2: Understand GIL and mutex combined effect

    Mutex ensures only one thread updates count at a time, so all increments are counted correctly.
  3. Final Answer:

    5000 -> Option D
  4. Quick Check:

    Mutex + GIL = correct count [OK]
Quick Trick: Use Mutex to avoid race conditions despite GIL [OK]
Common Mistakes:
  • Ignoring mutex and expecting race conditions
  • Thinking GIL alone prevents race conditions
  • Assuming code raises an error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes