progress

~/problems / Locks / Reader-writer and modal locks

A simple reader-writer lock

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

A plain Lock lets one thread in at a time, but readers change nothing, so many can look at the data together. Only a writer must be alone.

Implement RWLock:

  • acquire_read(): block while a writer holds the lock, then enter. Any number of readers may be in at once.
  • acquire_write(): block until nobody holds the lock, then enter as the only writer.
  • release_read() / release_write(): leave.
rw = RWLock()
# threads R1, R2: rw.acquire_read()   -> both get in together
# thread W:       rw.acquire_write()  -> blocks until R1 and R2 have both called release_read()
# thread R3:      rw.acquire_read()   -> blocks while W holds the lock, gets in after release_write()

No fairness needed: a stream of readers may keep a writer waiting. Acquires and releases are always paired. Don't sleep or busy-wait.

Show hint

keep readers (a count) and writer (a bool) behind one threading.Condition: readers wait_for(not writer), writers wait_for(not writer and readers == 0), and releases call notify_all().

Topic: Reader-writer and modal locks. Many readers or one writer; fairness so writers don't starve.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc