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

See it run

Threads around one lock: who is inside, who sleeps, and which policy let them.

Operations

Many or one

Three readers share. A writer waits, writes alone, and the readers come back together.

Step 1 of 8

Free

R1ReaderstateidleR2ReaderstateidleR3ReaderstateidleWWriterstateidlelockReadWriteLockreaders0writernowaiting0

No reader, no writer.

Step 1: Free

def acquire_read(self):    with self._cond:        wait until not writer and waiting == 0        self._readers += 1def release_read(self):    with self._cond:        self._readers -= 1        if self._readers == 0: notify_all()def acquire_write(self):    with self._cond:        self._waiting_writers += 1        wait until not writer and readers == 0        self._waiting_writers -= 1        self._writer = True
Watch
The number of readers
Result
Hand-over at zero

Only the last reader wakes anybody.

In the real world

The same read-write lock doing real jobs. Pick one and step through it.

Readers without a lock: one reference, frozen tables.

Step 1 of 4

Everybody on table 1

tillReaderusestable 1managerWriterdoesnothingnowReferencepoints totable 1table 1frozen Maptea300cake400loadtable 1

The till loads the reference once.

Step 1: Everybody on table 1

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Upgrading

    critical

    Two threads wait for each other. In Java one thread is enough.

    Wrong
    with lock.reading():    if missing:        with lock.writing(): add()
    Right
    with lock.reading():    found = not missingif not found:    with lock.writing():        if missing: add()
  • Locking each value

    critical

    A change fits between two reads that belong together.

    Wrong
    a = prices.get("tea")      # locksb = prices.get("cake")     # locks again
    Right
    total = prices.total(["tea", "cake"])   # one lock
  • Returning the inner map

    critical

    The caller reads it later, without any lock.

    Wrong
    with self._lock.reading():    return self._prices
    Right
    with self._lock.reading():    return dict(self._prices)
  • Release without finally

    critical

    After one exception the counter never reaches 0 again.

    Wrong
    lock.acquire_read()x = compute()lock.release_read()
    Right
    with lock.reading():    x = compute()
  • Slow work inside

    major

    One reader in a network call holds up a writer, and the writer holds up all readers.

    Wrong
    with lock.reading():    send(http, data)
    Right
    with lock.reading():    copy = dict(data)send(http, copy)
  • A get that writes

    major

    Two readers change the list at the same time.

    Wrong
    with lock.reading():    order.move_to_end(key)
    Right
    with lock.writing():    order.move_to_end(key)

Interview tips

  • Ask first

    • What must agree?
    • How long is a read?
    • May it be a little old?
  • Name the policy

    • Who waits behind whom?
    • Who can starve?
    • What does my library do?
  • Hide the lock

    • Inside the class.
    • Guards only.
    • Copies out.
  • Avoid the traps

    • No upgrade.
    • No nested read.
    • No foreign code inside.
  • Measure

    • Plain lock first.
    • Snapshot for short reads.
    • Longest wait of a writer.