liveBook · Manning

Rwmutex

As explained in Learn Go with Pocket-Sized Projects

sync.RWMutex is Go's synchronization type that permits concurrent readers while excluding writers.

sync.RWMutex protects shared data while allowing multiple goroutines to read concurrently. RLock and RUnlock guard read-only access; Lock and Unlock exclude both readers and writers. section 7.3.4

Use RWMutex deliberately when protecting a resource such as a cache:

  • Store a sync.RWMutex beside the protected data. section 7.3.4
  • Use RLock and RUnlock in methods that only read. section 7.3.4
  • Use Lock and Unlock in methods that modify data. section 7.3.4
  • Prefer sync.Mutex by default; benchmark before choosing RWMutex for performance, because its richer interface permits locking mistakes. section 7.3.4

A cache with read/write locking

A cache can use sync.RWMutex so concurrent Read calls do not block one another, while Upsert and Delete acquire the exclusive lock. Running go test -race . verifies that the change has not introduced a data race. section 7.3.4

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines read and write locking, applies each method to a cache, and defers performance validation to benchmarking.
Examples
Uses a generic cache with Read, Upsert, and Delete methods as the concrete synchronization example.
What it assumes
Assumes familiarity with Mutex locking and teaches the distinction between shared reads and exclusive writes.
What you can do after
Apply it to a cache and verify the synchronization with go test -race . and targeted benchmarks.
How it connects
Connects Mutex, caching, goroutines, data races, race testing, and benchmarking.

Also explained in

Compare how 4 books explain rwmutex →

Related concepts

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