When would you use Sync Mutex Basics in a real project
Fast recall
Quick revision
Core answer
Practical understanding of Sync Mutex Basics.
Repeating a definition without saying when to use it.
Give one trade-off and say how you would test it.
Interview-ready guide
Interview answer
The lock shapes:
var m sync.Mutex // ONE at a time, any access
var rw sync.RWMutex // RLock: many readers; Lock: one writer
rw.RLock() // reader — doesn't block other RLocks
rw.RUnlock()
rw.Lock() // writer — blocks ALL
rw.Unlock()Executed: three concurrent RLocks all entered simultaneously (all 3 printed 'reading'). A Mutex would have serialized them.
RWMutex rules: RLock and RLock coexist. Lock blocks everything. A pending Lock also blocks NEW RLocks (writer priority — anti-starvation).
When RWMutex wins: read-heavy cache (1000 reads per write, meaningful read sections). When it loses: writes frequent (Lock serializes everything — you got Mutex behavior plus complexity) or reads tiny (RLock/RUnlock overhead exceeds the parallelization).
The guidance: start with Mutex (simpler, faster almost always). Switch when profiling shows lock contention on a read-mostly path.
When would you use Sync Mutex Basics in a real project
Direct Answer
Mutex: one goroutine total. RWMutex: many concurrent READERS, one exclusive WRITER. RWMutex wins when reads vastly outnumber writes and the read section is meaningful.
Deep Dive & Architecture
RWMutex's state machine: a counter (negative = writer holds; positive = reader count) plus a writer-pending flag. RLock increments readers and proceeds (if no writer). Lock sets writer-pending, waits for readers to reach zero, flips to held — new RLocks queue behind (anti-starvation).
The complexity cost: RWMutex's transitions are more work than Mutex's single CAS. An uncontended RLock is fast, but a contended mix produces more scheduling churn than the same workload on a Mutex. Benchmark your actual contention pattern.
The anti-pattern the distinction enables: RLock around a map read is safe for the map structure, but if the value is a pointer, the POINTED-TO data needs its own sync — RLock protects the map, not the pointees. If the 'read' mutates anything (caching into the map), it's a write wearing a read lock.
Common Mistakes & Pitfalls
Repeating a definition without saying when to use it.
Check your understanding
Answer these without looking back at the article.
- What is Sync Mutex Basics, and when would you use it?
- How would you compare Sync Mutex Basics with an alternative?
- What is a common mistake when using Sync Mutex Basics?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.