Bird
0
0

Find the problem in this Ruby code snippet:

medium📝 Debug Q7 of 15
Ruby - Concurrent Programming
Find the problem in this Ruby code snippet:
mutex = Mutex.new
threads = 2.times.map do
  Thread.new do
    mutex.synchronize do
      puts 'Start'
      sleep 1
      puts 'End'
    end
  end
end
threads.each(&:join)
AThe code will print 'Start' and 'End' messages sequentially, blocking threads.
BMutex is not used correctly; it should be locked manually.
CThreads will run in parallel without waiting.
DThe sleep call causes a syntax error.
Step-by-Step Solution
Solution:
  1. Step 1: Understand mutex synchronize behavior

    Synchronize locks mutex for entire block, so only one thread runs it at a time.
  2. Step 2: Analyze output order

    Threads print 'Start', sleep 1 second, then 'End' sequentially, blocking each other.
  3. Final Answer:

    The code will print 'Start' and 'End' messages sequentially, blocking threads. -> Option A
  4. Quick Check:

    Mutex synchronize blocks threads sequentially [OK]
Quick Trick: Mutex synchronize blocks threads one at a time [OK]
Common Mistakes:
  • Expecting parallel prints
  • Thinking manual lock needed with synchronize
  • Assuming sleep causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes