liveBook · Manning

Write-preferring readers-writer lock

As explained in Learn Concurrent Programming with Go

A write-preferring readers-writer lock is a readers-writer synchronization lock that prioritizes waiting writers to prevent prolonged writer blocking.

A write-preferring readers–writer lock allows concurrent readers but gives waiting writers priority. Once a writer is waiting, new readers stop acquiring the lock, preventing readers from repeatedly delaying the writer. section 5.1.4

Why read preference can fail

Imagine two reader goroutines repeatedly acquiring a read lock, sleeping for one second, printing “Read done,” and unlocking. A writer that calls WriteLock() may remain blocked while readers continue arriving; the output repeats “Read done” indefinitely without “Write finished.” This is writer starvation. section 5.1.4

The lock tracks active readers, waiting writers, and whether a writer is active. A condition variable paired with a mutex suspends goroutines until those state conditions change. section 5.1.4

Go’s sync.RWMutex follows this write-preferring behavior: a blocked Lock call excludes new readers until the existing readers release their locks. A short run can therefore produce “Read done,” “Read done,” and then “Write finished.” section 5.1.4

How Learn Concurrent Programming with Go covers it

How deep it goes
Explains starvation, lock state, acquisition conditions, unlock broadcasts, and a Go implementation outline.
Examples
Uses looping readers, a blocked writer, execution output, and annotated ReadLock, WriteLock, and unlock functions.
What it assumes
Assumes mutex-based critical sections and develops condition-variable waiting, broadcasting, and starvation prevention.
What you can do after
Apply it via Go’s sync.RWMutex or implement its state transitions with sync.Cond and a mutex.
How it connects
Connects readers–writer locks with mutexes, condition variables, starvation, and Go’s sync.RWMutex.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Concurrent Programming with Go. The section links point to the parts of the book it draws on.