sync.Mutex
Channels are perfect when goroutines need to communicate. But sometimes you just need to protect a piece of shared state — no messaging required. That’s where a mutex comes in.
Mutual exclusion means only one goroutine can access a section of code at a time. Go’s sync.Mutex provides exactly that with two methods:
Lock— claim exclusive accessUnlock— release it
Wrap the code you want to protect between Lock and Unlock. Only one goroutine gets through at a time; the rest wait.
For cleanup, pair Lock with defer Unlock — as shown in the Value method. The mutex unlocks the moment the function returns, even if it panics.
Try it: remove the Lock/Unlock calls and run 1000 concurrent increments. The final count will be wrong — that’s a data race in action.