0
0
Rubyprogramming~10 mins

Thread synchronization with Mutex in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Thread synchronization with Mutex
Start Threads
Thread tries to lock Mutex
Access shared
resource
Unlock Mutex
Threads finish
Threads try to lock a mutex before accessing shared data. If locked, others wait. After use, mutex unlocks allowing next thread.
Execution Sample
Ruby
require 'thread'

mutex = Mutex.new
counter = 0

threads = 2.times.map do
  Thread.new do
    mutex.synchronize do
      temp = counter
      sleep(0.1)
      counter = temp + 1
    end
  end
end
threads.each(&:join)
puts counter
Two threads safely increment a shared counter using a mutex to avoid conflicts.
Execution Table
StepThreadActionMutex Locked?counter ValueNotes
1Thread 1Attempts to lock mutexNo0Mutex is free, Thread 1 locks it
2Thread 1Reads counter into tempYes0temp = 0
3Thread 1Sleeps (simulate work)Yes0Holding lock during sleep
4Thread 1Sets counter = temp + 1Yes1counter updated to 1
5Thread 1Unlocks mutexNo1Mutex released
6Thread 2Attempts to lock mutexNo1Mutex free, Thread 2 locks it
7Thread 2Reads counter into tempYes1temp = 1
8Thread 2Sleeps (simulate work)Yes1Holding lock during sleep
9Thread 2Sets counter = temp + 1Yes2counter updated to 2
10Thread 2Unlocks mutexNo2Mutex released
11MainPrints counterNo2Final counter value is 2
💡 Both threads completed, mutex unlocked, counter incremented safely to 2
Variable Tracker
VariableStartAfter Thread 1After Thread 2Final
counter0122
mutex Locked?NoNoNoNo
Key Moments - 3 Insights
Why does the counter not become 1 instead of 2 after both threads run?
Because each thread locks the mutex before reading and updating counter, they run one after another safely (see execution_table steps 1-5 and 6-10). This prevents race conditions.
What happens if a thread tries to lock the mutex while it is already locked?
The thread waits (blocks) until the mutex is unlocked by the other thread, as shown in the flow where one thread locks and the other waits.
Why do we use mutex.synchronize instead of manually locking and unlocking?
mutex.synchronize ensures the mutex is always unlocked even if an error occurs inside the block, making code safer and simpler (see code sample).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of counter after Thread 1 unlocks the mutex?
A0
B1
C2
DUndefined
💡 Hint
Check step 5 in the execution_table where Thread 1 unlocks the mutex and counter is updated.
At which step does Thread 2 acquire the mutex lock?
AStep 9
BStep 2
CStep 6
DStep 11
💡 Hint
Look at the 'Mutex Locked?' column in the execution_table for Thread 2 locking the mutex.
If we remove the mutex, what problem would most likely happen?
ARace condition causing incorrect counter value
BThreads run sequentially without issues
CCounter increments correctly to 2
DProgram crashes immediately
💡 Hint
Think about why mutex is used in the code sample and what happens if threads access shared data simultaneously.
Concept Snapshot
Mutex ensures only one thread accesses shared data at a time.
Use mutex.synchronize { ... } to lock and unlock safely.
Threads wait if mutex is locked, preventing race conditions.
Without mutex, shared data can be corrupted.
Mutex unlocks automatically after block ends.
Full Transcript
This example shows two threads incrementing a shared counter safely using a mutex. Each thread locks the mutex before reading and updating the counter, then unlocks it. The execution table traces each step, showing when threads lock, read, sleep, update, and unlock. The variable tracker shows counter changes from 0 to 2. Key moments clarify why mutex prevents race conditions and why synchronize is safer. The quiz tests understanding of mutex locking steps and consequences of removing mutex.