Module lessons (4/5)
`sync.Mutex` and `sync.WaitGroup`
When channels are not enough: protect shared state with Mutex, wait N goroutine with WaitGroup.
What you'll learn in this lesson
- Protect shared memory against data races using
sync.Mutex(mu.Lock()+defer mu.Unlock()) andsync.RWMutex. - Wait for the
Ngoroutine to complete viasync.WaitGroup(Add,Done,Wait) without deadlock or race. - Use
sync.Oncefor thread-safe singleton initializations and validate your code with the-raceflag.
Overview
When orchestrating the flow is the primary focus, channels shine; when you need to protect a shared struct, cache or counter in memory between multiple goroutines, sync.Mutex is simpler, faster and more idiomatic.
Its zero value is already a ready-to-use unlocked state (var mu sync.Mutex). Protect each critical section with Lock() and defer Unlock() to ensure release even in the presence of early returns or panics:
Sections covered in this lesson
- 1
sync.Mutexanddefer mu.Unlock() - 2
sync.WaitGroupto wait for N goroutine - 3
sync.Onceand the flag-race - 4Guided practice
- 5Check for understanding
Unlock "`sync.Mutex` and `sync.WaitGroup`" and the full Course Go curriculum
When channels are not enough: protect shared state with Mutex, wait N goroutine with WaitGroup.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Go plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.