The sync package provides Go’s mutex synchronization primitive. A mutex lets only one goroutine enter a critical section at a time, preventing concurrent updates from producing a race condition. section 4.1.1
Use a mutex around every access to shared state:
- Create an initially unlocked sync.Mutex. section 4.1.1
- Call Lock before entering the critical section. section 4.1.1
- Call Unlock immediately after the protected operation; waiting goroutines then compete for the mutex. section 4.1.1
Protecting a shared account balance
Two goroutines repeatedly add to and subtract from a shared money variable. Passing both a pointer to the variable and a shared mutex ensures that each update occurs alone; the demonstrated result is 100.


