Bird
0
0

Identify the problem in this Ruby code using Mutex and how to fix it:

medium📝 Debug Q14 of 15
Ruby - Concurrent Programming
Identify the problem in this Ruby code using Mutex and how to fix it:
require 'thread'
mutex = Mutex.new
counter = 0
threads = 2.times.map do
  Thread.new do
    mutex.lock
    counter += 1
  end
end
threads.each(&:join)
puts counter
AThreads are not joined properly; fix by joining inside the thread block
BMutex is not needed here; remove mutex.lock
Ccounter should be initialized inside the thread
DMissing mutex.unlock causes deadlock; fix by adding mutex.unlock after increment
Step-by-Step Solution
Solution:
  1. Step 1: Check mutex usage

    Mutex is locked but never unlocked, causing threads to wait forever (deadlock).
  2. Step 2: Fix by unlocking mutex

    After increment, call mutex.unlock or better use mutex.synchronize to auto-handle locking/unlocking.
  3. Final Answer:

    Missing mutex.unlock causes deadlock; fix by adding mutex.unlock after increment -> Option D
  4. Quick Check:

    Always unlock mutex after lock to avoid deadlock [OK]
Quick Trick: Always unlock mutex or use synchronize block [OK]
Common Mistakes:
  • Forgetting to unlock mutex
  • Removing mutex when needed
  • Initializing shared data inside threads incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes