Bird
0
0

Find the problem in this Ruby code:

medium📝 Debug Q7 of 15
Ruby - Concurrent Programming
Find the problem in this Ruby code:
mutex = Mutex.new
counter = 0
threads = 2.times.map do
  Thread.new do
    3.times do
      mutex.lock
      counter += 1
    end
    mutex.unlock
  end
end
threads.each(&:join)
puts counter
ACounter is incremented outside the lock
BMutex is never locked
CMutex is unlocked only once after multiple locks, causing deadlock
DThreads are not joined properly
Step-by-Step Solution
Solution:
  1. Step 1: Check lock/unlock pairing

    Mutex is locked 3 times inside loop but unlocked only once after loop.
  2. Step 2: Identify consequence

    This causes deadlock because locks are not properly released.
  3. Final Answer:

    Mutex is unlocked only once after multiple locks, causing deadlock -> Option C
  4. Quick Check:

    Lock/unlock must match count [OK]
Quick Trick: Unlock Mutex as many times as you lock it [OK]
Common Mistakes:
  • Unlocking once after multiple locks
  • Assuming one unlock frees all locks
  • Not locking Mutex before increment

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes