sync.RWMutex: many readers at once, one writer alone

Read the explanation
What if

Two readers hold the read lock at the same time. The writer waits in Lock until both have let go, then changes price on its own.

0123456RLock: reading priceRLock: reading priceLock: waits for the readerswriter: Lock: price = 2write

Tap any block to see what that thread is doing.

  • Holding lock
  • Waiting / parked
Step 1/4

Both readers call RLock. A read lock can be shared, so neither waits.

1var (2    mu    sync.RWMutex3    price = 14)5 6func reader(name string) {7    mu.RLock() // many readers may hold it at once8    defer mu.RUnlock()9    time.Sleep(20 * time.Millisecond) // a slow read10    fmt.Println(name, "read price", price)11}12 13func writer() {14    mu.Lock() // waits until no reader holds it15    defer mu.Unlock()16    price = 217    fmt.Println("writer set price 2")18}

Explanation

What just happened

Both readers held the read lock at the same time. The writer’s Lock waited until both had let go, then changed price with the lock to itself.

Try the what-if switch

Why

A read lock is safe to share: readers don’t change anything. A write needs the data to itself, so nobody sees a half-done change. And once a writer waits, new readers queue behind it, or a steady stream of readers could starve it.

When to use it

For a value or map that is read far more often than it is written, with reads slow enough to be worth running at once. For short, even mixes, a plain sync.Mutex is simpler.

Watch out

You can’t upgrade: a goroutine holding RLock that calls Lock waits for itself forever.

Common questions

What's the difference between RLock and Lock?

Many goroutines can hold RLock at the same time; Lock is held by one goroutine alone. A writer's Lock waits, in [sync.RWMutex.Lock], until every reader has called RUnlock.

Why does RLock block when only readers hold the lock?

Because a writer is waiting. Once one is, a new RLock waits behind it, in [sync.RWMutex.RLock], and TryRLock returns false, so the writer isn't kept out by a stream of readers.

Can I upgrade an RLock to a Lock?

No. Lock waits for every reader to leave, including the goroutine that asks, so it never returns; with nothing else running, Go stops with all goroutines are asleep - deadlock!

Should I use RWMutex instead of Mutex?

When reads are many and slow and writes are rare: then readers run at once instead of taking turns. For short reads, or as many writes as reads, a plain sync.Mutex is simpler.

Verified: this timeline matches a real program, checked in CI on Go 1.26 and 1.27. How we verify. Unclear or wrong? Tell us