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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping every access — reads included — in the same mutex is what makes the whole object thread-safe.
- 2`synchronize` returns its block's value, so guarded methods can read and return state in one atomic step.
- 3Passing a block lets callers run arbitrary read-modify-write logic atomically without exposing the lock.
Related explainers
ruby
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-thread-safe-counter-with-mutex-in-ruby-explained-ruby-021b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.