AlgoViz

Mutexes and reader–writer locks

medium 4 min

A mutex gives one holder exclusive access.

Video lesson · Chapter 1 of 5

Two readers follow the old index

0:00 / 3:17

Read-write lock

1:04Reel

Theory

Read or listen first. About 1 min.

What it is

Imagine two threads consulting an immutable index while a third needs to replace it. Reading together is compatible. Replacing the index needs exclusive access to the protected state.

Which accesses can overlap?

TimeRead ARead indexRead BRead indexWriterWaitingReplaceThe writer begins when both readers release.
Both readers hold shared locks together. The writer waits until the last reader releases the index.

Why it exists

The shape of the workload determines whether concurrent readers help. With frequent writes, the time spent waiting for readers to drain can dominate.

Words to know

Read lock
A shared lock that permits other readers to enter while excluding an exclusive writer.

How it works

Step through the idea, or press Play.

Step 1 of 3

Read together. Two readers hold compatible read locks.

Understand it

Worked example

Mutexes and reader–writer locks in practice

An index reader copies a pointer under a read lock. If it later mutates the pointed-to object after releasing the lock, the mutation is outside the protected region. Publish immutable snapshots or protect the entire mutation.

Related case

Sharing a worker pool safely

A thumbnail service has eight GPU slots. Two handlers both read “one free” before either records its claim. Which operation needs to be indivisible?

The workshop key rack
The workshop key rack1234567freeSeven machines are busy

Release once after completion.

Sources