Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Concurrent Programming
What will be the output of this Ruby code?
require 'thread'
mutex = Mutex.new
counter = 0
threads = 5.times.map do
  Thread.new do
    10.times do
      mutex.synchronize { counter += 1 }
    end
  end
end
threads.each(&:join)
puts counter
A10
B0
C5
D50
Step-by-Step Solution
Solution:
  1. Step 1: Analyze thread and loop counts

    There are 5 threads, each incrementing counter 10 times, total increments = 5 * 10 = 50.
  2. Step 2: Understand Mutex protection

    Mutex ensures increments happen safely without lost updates, so counter will be exactly 50.
  3. Final Answer:

    50 -> Option D
  4. Quick Check:

    5 threads * 10 increments = 50 [OK]
Quick Trick: Multiply threads by increments with Mutex [OK]
Common Mistakes:
  • Ignoring Mutex and expecting less than 50
  • Confusing thread count with increments
  • Assuming race conditions reduce count

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes