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 = 3.times.map do
  Thread.new do
    2.times do
      mutex.synchronize { counter += 1 }
    end
  end
end
threads.each(&:join)
puts counter
A2
B3
C6
D0
Step-by-Step Solution
Solution:
  1. Step 1: Count total increments

    There are 3 threads, each increments counter 2 times, total 3*2=6 increments.
  2. Step 2: Understand mutex effect

    Mutex ensures increments happen safely without losing counts, so final counter is 6.
  3. Final Answer:

    6 -> Option C
  4. Quick Check:

    3 threads * 2 increments each = 6 [OK]
Quick Trick: Multiply threads by increments inside synchronize block [OK]
Common Mistakes:
  • Ignoring mutex and expecting wrong count
  • Counting only one thread's increments
  • Confusing thread join effect

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes