Locking protects shared state when multiple goroutines may use it at once. A mutex acts as a gatekeeper: one goroutine receives exclusive access while others wait, preventing races that can otherwise cause stale writes, crashes, or data corruption. A mutex begins unlocked; Lock acquires exclusive access and Unlock lets a waiting goroutine proceed. section 8.2.4
Use a mutex around the resource whose operations must not overlap, not around unrelated work. For straightforward shared-state protection, mutexes are simpler and generally more efficient than routing state changes through channels, which primarily coordinate goroutines and add synchronization overhead. section 8.2.4 section 8.10
A practical locking pattern is:
- Store a sync.RWMutex alongside the shared map in the owning type. section 8.2.4
- Use Lock before changing the map, and defer Unlock immediately so every return path releases exclusive access. section 8.2.4 section 8.10
- Use RLock and defer RUnlock for lookups when concurrent reads may proceed but writes must remain exclusive. section 8.2.4
Protecting an in-memory link service
A Shortener shared by HTTP handlers stores links in a map. Since requests run in separate goroutines, Shorten takes the write lock before checking, initializing, and saving a link. Resolve takes a read lock before retrieving one. This keeps the service safe for concurrent use while allowing multiple readers. section 8.2.4 section 8.2
Figure 8.5 Multiple goroutines using the same state may cause race conditions. A mutex gives them safe, orderly access to the shared state.
Compare unsynchronized concurrent map access with mutex-guarded access that orders operations and prevents stale writes. section 8.2.4

















