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
- a writer is waiting: reader 2 arrives after the writer started waiting, and waits too, though only a reader holds the lock.
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