AlgoViz

Read-write lock

medium 50 min

Many readers or one writer, never both.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:32

Read-write lock

1:04Reel

Theory

Read or listen first. About 2 min.

What it is

A read-write lock is a lock with two modes. In shared mode any number of threads may hold it, to read. In exclusive mode exactly one thread holds it, to write, and nobody reads meanwhile.

It keeps the promise of an ordinary lock, that nobody sees a half-finished change, and adds one freedom: readers do not wait for readers.

Two decisions are hidden in each implementation. Who goes next when both kinds wait, and whether a thread may change its mode or enter twice.

Why it exists

Much data is read far more often than changed: prices, settings, routes, permissions. Two reads can not disturb each other, so making them wait is waste.

The gain is real when reading takes a while and several cores read at once. Then eight cores do up to eight times as much.

It is also a way to say something in code. A method that takes the read lock promises not to change anything, and a reviewer can check that.

The costs are real as well: bookkeeping per read, a writer that may starve, and two traps that a plain lock does not have.

A short history

  1. 1971

    Courtois, Heymans and Parnas publish Concurrent control with readers and writers in October. It states the problem with two versions: no reader waits for a waiting writer, and no writer waits longer than necessary.

  2. 2004

    Java 5 adds ReentrantReadWriteLock in java.util.concurrent.locks, with an optional fair mode and downgrading.

  3. 2010

    Brandenburg and Anderson's article on spin-based reader-writer synchronization for real-time systems appears online. It covers phase-fair locks, where readers and writers take turns in phases.

  4. 2014

    Java 8 adds StampedLock with optimistic reading.

  5. 2017

    C++17 adds std::shared_mutex.

Words to know

Shared mode
The read lock. Many holders.
Exclusive mode
The write lock. One holder, alone.
Torn read
A mixture of old and new values that never existed together.
Starvation
A thread that could go on is passed over again and again.
Barging
A newcomer enters before those who wait.
Upgrade
From read to write without releasing. Two at once is a deadlock.
Downgrade
From write to read without a gap. Safe.
Reentrant
The thread that holds the lock may take it again.
Optimistic read
Read without a lock, then check whether a writer came in between.
Snapshot
A version of the data that never changes, reached by one reference.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

Share. Readers enter together and are counted.

Understand it

Story

The hall with one mosaic

Looking at something does not change it. So ten people may look at the same time. Changing it is different: while it is being changed, a person who looks sees something that never existed.

Fish, half a bird, bird
inside0

The board counts readers. The rope is the policy. The closed door is the write lock.

Four participants

  • ReadWriteLock

    Counts readers, knows whether a writer is inside, and decides who is next. ReentrantReadWriteLock, RWMutex, shared_mutex.

  • Read lock (shared)

    Many may hold it. It blocks writers, not other readers.

  • Write lock (exclusive)

    One may hold it. It blocks readers and other writers.

  • Readers and writers

    Threads that promise to take the right lock and to release it. The lock can not check what they do inside.

Who may join whom

HoldingA reader asksA writer asks
Nobodyentersenters
Readersenters (if no writer is waiting)waits
A writerwaitswaits
Only one cell differs from an ordinary lock. Everything on this page is about that cell.

The problem

What goes wrong without it

A shop has a price list. Forty tills ask it all day, and a manager changes it a few times. A change often touches two prices that belong together: the tea becomes dearer, the cake cheaper, the set stays at 700.

Python
prices = {"tea": 300, "cake": 400}def total():    return prices["tea"] + prices["cake"]def change(between):    prices["tea"] = 320    between()                       # a till asks at this moment    prices["cake"] = 380seen = []print(total())                      # 700change(lambda: seen.append(total()))print(seen)                         # [720], a price that never existedprint(total())                      # 700assert seen == [720]
No lock. The reader is placed exactly between the two writes, so the bug shows each time.
Edit and run it in your browser

This is a torn read: half old, half new. An ordinary lock repairs it. It also makes forty tills stand in one line for something that none of them changes. If reading takes long, that line is the shop's speed limit.

The design that hurts

guards?Lock- held: boolean+ lock()+ unlock()PriceList+ prices: Map+ get(item)+ set(item, cents)

1/3The lock lies beside the data

Nothing forces anyone to take it. A new report class reads the prices without it, and no test notices.

usesdepends on

Three repairs: put the lock inside, make a change one call, and let readers share.

The idea

A lock with two doors

The lock offers two handles to the same state. Both look like ordinary locks, so code can be handed the one it needs and nothing more.

Read-write lock in general

«interface»ReadWriteLock+ readLock(): Lock+ writeLock(): Lock«interface»Lock+ lock()+ unlock()+ tryLock(): boolean

1/5Two small interfaces

ReadWriteLock hands out two locks. Lock is what everybody knows: lock, unlock, try.

implementsowns (dies together)

Named after Java's classes. Go puts both pairs of methods on one type, C++ uses two guard classes on one shared_mutex.

Readers, then a writer, then readers

The hand-over happens at zero and at nothing else.

The lock as a state diagram

There is no arrow from Reading to Writing. That missing arrow is the upgrade, and it has a section of its own.

Five scenes to know

SceneCallResult
Several readersread lock, read lockBoth at once
A writer waitswrite lock while readers are inSleeps until the last one leaves
A writer is inread lock or write lockSleeps
A reader behind a waiting writerread lockDepends on the policy
TrytryLock while a writer is inFalse at once, the thread does something else

The promise

(writers=0∧readers≥0)∨(writers=1∧readers=0)(\text{writers} = 0 \land \text{readers} \ge 0) \lor (\text{writers} = 1 \land \text{readers} = 0)
Assert this inside every lock and unlock while you develop.

Policy

Who goes next?

The rule many or one says nothing about the line outside. With a writer waiting and a new reader arriving, somebody must decide. Any choice hurts somebody.

Readers are inside, a writer waits, a new reader arrives.

BreaksReaders first
How
The new reader enters.
Limit
If reads overlap without a gap, the counter never reaches 0 and the writer waits for ever.
Choose when
Writers that may wait any time, or readers that come in clear waves.
WorksWriters first
How
New readers wait while any writer waits.
Limit
A steady stream of writers starves readers. A thread that reads twice, nested, can block itself.
Choose when
Rare writes that should be seen soon. This is what we build.
StrongFirst come, first served, readers in groups
How
One line. Neighbouring readers enter together.
Limit
A little slower: groups are smaller. Nested reads are still dangerous.
Choose when
When neither side may starve. See the FAANG page Policies.
Python
from collections import dequedef play(arrivals, policy, read=2, write=2, limit=60):    """Time steps instead of threads. arrivals: {time: 'R' or 'W'}. Returns who entered when."""    wait, inside, entered, t, n = deque(), [], [], 0, {"R": 0, "W": 0}    while t < limit and (arrivals.keys() - range(t) or wait or inside):        inside = [(k, end) for k, end in inside if end > t]        for kind in arrivals.get(t, ""):            n[kind] += 1            wait.append((kind, f"{kind}{n[kind]}"))        while True:            writing = any(k == "W" for k, _ in inside)            if writing or not wait:                break            can = [w for w in wait if w[0] == "R" or not inside]            if policy == "readers first":                can.sort(key=lambda w: w[0])                 # R before W            elif policy == "writers first":                can = [w for w in can if w[0] == "W" or all(x[0] == "R" for x in wait)]            else:                                            # fair: only the head of the line                can = [w for w in can if w is wait[0]]            if not can:                break            kind, name = can[0]            wait.remove(can[0])            inside.append((kind, t + (read if kind == "R" else write)))            entered.append((name, t))        t += 1    return enteredstream = {0: "R", 1: "RW", 2: "R", 3: "R", 4: "R", 5: "R", 6: "R", 7: "R"}for policy in ("readers first", "writers first", "fair"):    out = play(stream, policy)    print(f"{policy:14}", "W1 enters at", dict(out)["W1"], "| last reader at", max(t for n, t in out if n[0] == "R"))
Time steps instead of threads. Eight readers arrive one per step, each reads for two steps, one writer arrives at step 1.
Edit and run it in your browser

Readers first let the writer in at step 9, when the stream had ended. With a stream that never ends the answer is never. The other two policies let it in at 2 and 3.

What your library does

LibraryPolicyAgain by the same thread?
Java ReentrantReadWriteLockUnspecified order by default, about first come with trueYes. Write then read works, read then write waits for ever
Go sync.RWMutexA blocked writer excludes new readersNo. Not for reading either
Rust std::sync::RwLockDepends on the system, no promiseMay deadlock or panic
C++ std::shared_mutexLeft to the implementationUndefined behavior
POSIX on glibcPrefers readers by default, can be setReads may be nested in that default
From the documentation of each. Do not write code that depends on one of these and then port it.

Judgement

When to use it and when not

A read-write lock is more expensive than a plain lock. Each reader must change the counter when it enters and leaves. It pays only if reading itself takes clearly longer than that, and if reads really overlap.

Fits

  • Many more reads than writes
  • Reads that take a while: search, copy, sum
  • Several processor cores that really read at once
  • Data that must change in place
  • Caches, routing tables, configuration, permissions

Does not fit

  • Many writes: it becomes a slow plain lock
  • Reads of a few nanoseconds: the counter is the bottleneck
  • A single value: use an atomic reference
  • One thread, or no overlap
  • Reading that secretly writes, such as a cache that counts hits

Which protection?

Connection pools are not on this picture: a pool gives out different things to each thread, which is a semaphore.

The price

  • Cost per read

    Two changes of one shared counter, seen by all cores.

  • Starvation

    Somebody may wait very long, depending on the policy.

  • New traps

    Upgrade and nested reads. A plain lock does not have them.

  • A promise by hand

    Nothing stops a change under the read lock. Return copies, not the inner map.

Summary

The whole topic in one minute.

Many readers or one writer, never both. Three numbers are enough: readers, writer, waiting writers. Readers wait for the last two, writers for the first two.

Readers first starves writers, writers first starves readers, one line or phases starve nobody. A waiting writer that gives up must wake the others.

Never upgrade: release, take write, check again. Measure before replacing a plain lock, and think of a snapshot when readers may finish with the version they began with.

  • Many readers or one writer, never both.
  • The lock protects a moment: all values that belong together change under one write lock.
  • The policy decides who starves. Know the one of your library.
  • Write to read is possible (downgrade). Read to write is a trap (upgrade).
  • Measure. For short reads a plain lock wins, for old copies a snapshot wins.

Sources