ruby 31 lines · 6 steps

A thread-safe counter with Mutex in Ruby

How a single mutex guards every read and write so concurrent threads never corrupt a shared counter.

Explained by highlit
1class ThreadSafeCounter
2 def initialize(initial = 0)
3 @count = initial
4 @mutex = Mutex.new
5 end
6 
7 def increment(by = 1)
8 @mutex.synchronize { @count += by }
9 end
10 
11 def decrement(by = 1)
12 @mutex.synchronize { @count -= by }
13 end
14 
15 def value
16 @mutex.synchronize { @count }
17 end
18 
19 def reset
20 @mutex.synchronize do
21 previous = @count
22 @count = 0
23 previous
24 end
25 end
26 
27 # Atomically read-modify-write under a single lock
28 def update
29 @mutex.synchronize { @count = yield(@count) }
30 end
31end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Wrapping every access — reads included — in the same mutex is what makes the whole object thread-safe.
  2. 2`synchronize` returns its block's value, so guarded methods can read and return state in one atomic step.
  3. 3Passing a block lets callers run arbitrary read-modify-write logic atomically without exposing the lock.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A thread-safe counter with Mutex in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code