Skip to main content
Module 7 · Lesson 4 of 534/50 in the course~14 min
Module lessons (4/5)

`sync.Mutex` and `sync.WaitGroup`

Lesson preview5 hands-on exercises readyCourse Go · Module 7 — Competition

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()) and sync.RWMutex.
  • Wait for the N goroutine to complete via sync.WaitGroup (Add, Done, Wait) without deadlock or race.
  • Use sync.Once for thread-safe singleton initializations and validate your code with the -race flag.

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. 1sync.Mutex and defer mu.Unlock()
  2. 2sync.WaitGroup to wait for N goroutine
  3. 3sync.Once and the flag -race
  4. 4Guided practice
  5. 5Check for understanding
Pro Lesson · Module 7 — Competition

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.