Use RWMutex and compare contention
Use RWMutex and compare contention
RWMutex permits multiple readers or one exclusive writer. Use RLock/RUnlock for read-only critical sections and Lock/Unlock for modifications. It can help read-heavy workloads, but has overhead; measure rather than assuming it is faster than Mutex.
package main
import ( "fmt" "sync")
type Catalog struct { mu sync.RWMutex price int}
func (c *Catalog) Set(v int) { c.mu.Lock(); defer c.mu.Unlock(); c.price = v }func (c *Catalog) Get() int { c.mu.RLock(); defer c.mu.RUnlock(); return c.price }func main() { var c Catalog c.Set(12) var wg sync.WaitGroup out := make([]int, 3) for i := range out { wg.Add(1) go func(i int) { defer wg.Done(); out[i] = c.Get() }(i) } wg.Wait() fmt.Println(out)}The readers access distinct output slots, and the writer completed before they start. A waiting writer prevents new RLock calls from acquiring the lock until it has acquired and released it. Do not upgrade a read lock to a write lock or recursively acquire read locks; release and recheck instead.
Expected output:
[12 12 12]Observe lock compatibility
package main
import ( "fmt" "sync")
func main() { var mu sync.RWMutex mu.RLock() fmt.Println(mu.TryLock()) ok := mu.TryRLock() fmt.Println(ok) if ok { mu.RUnlock() } mu.RUnlock() mu.Lock() fmt.Println(mu.TryRLock()) mu.Unlock()}This controlled example has no competing goroutines. TryLock and TryRLock return immediately; unlock only after success. A failed try-lock establishes no synchronization relationship. In real workloads, avoid spinning on try-lock; usually blocking locks are clearer. Compare throughput under realistic read/write mixes and critical-section lengths; this is a compatibility check, not a benchmark.
Expected output:
falsetruefalseTry it locally
Create a protected string with Set and Get methods using RWMutex. Set "ready" and print it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Synchronization 02: Use RWMutex and compare contention
Check the lesson objective before moving on.
Can a writer and reader hold RWMutex simultaneously?
When is RWMutex preferable?