Dozens of passenger screens read a station's departure board, and now and then the dispatcher pushes an update. With a plain reader-writer lock (readers share; a writer waits until no reader is inside, as in Basics: a simple reader-writer lock), a busy station always has some screen inside, so the update never goes out.
Implement WriterFirstLock, a reader-writer lock that prefers writers:
acquire_read(): block while a writer holds the lock or any writer is waiting, then enter. Readers share.acquire_write(): announce you're waiting, block until nobody holds the lock, then enter alone.release_read()/release_write(): leave.
Readers already inside when a writer starts waiting finish normally; only new readers are held back.
rw = WriterFirstLock()
# screen S1: rw.acquire_read() -> gets in
# dispatcher: rw.acquire_write() -> waits for S1
# screen S2: rw.acquire_read() -> blocks too: a writer is waiting
# S1: rw.release_read() -> dispatcher gets in, updates, release_write()
# -> only now does S2 get in
Every waiting writer goes before any held-back reader: if two writers are waiting, both get in (one at a time) before a new reader does. Acquires and releases are paired, and no thread takes the read lock twice. Don't sleep or busy-wait.
Show hint
add a waiting_writers count: a writer increments it before wait_for(not writer and readers == 0) and decrements it once in; readers wait_for(not writer and waiting_writers == 0); releases call notify_all().