sync.Mutex and sync.RWMutex
Locking and read-write locking patterns
Why mutexes?
When multiple goroutines share mutable state, concurrent reads and writes cause data races. A mutex serialises access so only one goroutine enters the critical section at a time.
sync.Mutex basics
Lock before reading/writing shared state; Unlock after. Use defer to guarantee unlocking even if the function panics.
var mu sync.Mutex
var counter int
func inc() {
mu.Lock()
defer mu.Unlock()
counter++
}All lessons in this course
- sync.Mutex and sync.RWMutex
- sync.WaitGroup
- sync.Once and sync.Map
- Race Detector and Safe Patterns