Skip to content

Lesson 3 of 9 · 25m

Mutexes, Condition Variables, and Lock Granularity

How to protect invariants with mutexes, avoid the classic condition-variable mistakes, and choose lock granularity without turning the system into a convoy.

A mutex is not a magic thread-safety sticker. It protects a relationship between pieces of data — an invariant. When engineers say a mutex "protects the map" but the real invariant is "the map, the count, and the audit log move together," they have not actually locked the right thing. Most locking bugs are invariant bugs wearing synchronization clothing.

Lock around invariants, not variables

Suppose a bank account has a balance and a transaction count. The invariant is that they update together:

struct Account {
    balance: i64,
    transactions: u64,
}
struct LockedAccount {
    inner: Mutex<Account>,
}
fn deposit(account: &LockedAccount, cents: i64) {
    let mut inner = account.inner.lock().unwrap();
    inner.balance += cents;
    inner.transactions += 1;
}  // guard drops here; the invariant is never visible broken

Rust makes the idea explicit by tying the data to the mutex. In languages that do not, write down what each lock protects. A comment like // guarded by mu above fields is primitive but infinitely better than tribal knowledge.

Hold locks for the shortest correct time

A lock held while doing I/O, serialization, logging, or user callbacks creates a convoy. The pattern is simple: prepare outside the lock, mutate inside the lock, perform side effects after unlocking.

Event event;
synchronized (state) {
    event = state.apply(command);       // small, fast mutation
}
publisher.publish(event);               // outside the critical section

But "shortest" does not mean splitting an invariant into pieces. If two writes must look atomic, they belong in the same critical section even if that makes the lock slightly hotter.

Condition variables require a predicate loop

Condition variables are for waiting until the state satisfies a predicate. They can wake spuriously, and they do not remember missed signals, so the only correct shape is a loop:

std::unique_lock<std::mutex> lock(mu);
cv.wait(lock, [&] { return !queue.empty(); });
Job job = std::move(queue.front());
queue.pop();

The predicate matters. Without it, you can consume after another thread already drained the queue, or miss a signal sent before you started waiting. In Java the equivalent is while (!condition) { wait(); }, not a single if.

Granularity is a contention decision

One global lock is simple but serializes unrelated work. One lock per object increases parallelism but multiplies lock-ordering risk. Practical systems often use striped locks: hash a key to one of N independent locks.

stripes = [threading.Lock() for _ in range(64)]
lock = stripes[hash(key) % len(stripes)]

Striping is a compromise: unrelated operations usually proceed in parallel, and the lock-ordering surface stays small. It is not a correctness substitute — each stripe still protects a documented shard of state.

Field notes

  • Never call application callbacks while holding a structural lock. The callback can re-enter the subsystem and deadlock.
  • Recursive mutexes hide ownership bugs. Prefer restructuring so the same thread does not need the same lock twice.
  • notify_one is correct only when exactly one waiter can use the new state. Broadcast when the state change benefits multiple waiters.
  • Read-write locks are not automatically faster. Writer starvation and cache-line bouncing often make them worse than a mutex.
  • Lock-free does not mean faster either; a single well-placed mutex frequently wins at moderate contention.

Was this lesson helpful?

Sign in to rate