Bird
0
0

Examine this Ruby code snippet:

medium📝 Debug Q7 of 15
Ruby - Concurrent Programming
Examine this Ruby code snippet:
mutex = Mutex.new
counter = 0
threads = 4.times.map do
  Thread.new do
    25.times do
      mutex.synchronize { counter += 1 }
    end
  end
end
threads.each(&:join)
puts counter

What issue might still arise despite using a Mutex here?
AThe code will raise an exception due to improper Mutex usage.
BThe counter variable is not thread-safe even with Mutex.
CThreads may deadlock because Mutex is not released.
DNo issue; the Mutex correctly prevents race conditions.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze Mutex usage

    The code uses mutex.synchronize to protect increments to counter.
  2. Step 2: Understand thread safety

    This ensures only one thread modifies counter at a time, preventing race conditions.
  3. Step 3: Check for deadlocks or exceptions

    Mutex is properly used and released after each block, so no deadlocks or exceptions occur.
  4. Final Answer:

    No issue; the Mutex correctly prevents race conditions. -> Option D
  5. Quick Check:

    Mutex ensures safe increments [OK]
Quick Trick: Mutex protects shared data from race conditions [OK]
Common Mistakes:
  • Assuming Mutex is unnecessary for shared variables
  • Believing Mutex causes deadlocks without evidence
  • Thinking Mutex usage always raises exceptions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes