Mutexes and reader–writer locks
medium 4 minA mutex gives one holder exclusive access.
Video lesson · Chapter 1 of 5
Two readers follow the old index
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?
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.
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?
Release once after completion.