Advanced 20 min readModule: Module 10: Sync Primitives (Mutex, WaitGroup, Once)
sync.WaitGroup, sync.Mutex & Race Detector (-race)
Synchronize goroutine completion with WaitGroup, protect shared memory with Mutex, and detect race conditions.
What You Will Learn in This Lesson
- Waiting for N concurrent workers with sync.WaitGroup (Add, Done, Wait)
- Protecting critical shared variables with sync.Mutex and sync.RWMutex
- Running the Go Race Detector (go test -race) to catch data races
Introduction & Core Concept
When channels are not appropriate, the standard library 'sync' package provides classical low-level synchronization primitives like Mutexes and WaitGroups.
WHY DOES THIS MATTER IN THE REAL WORLD?
Running 'go run -race' detects subtle multithreaded memory corruption before code reaches production.
sync.WaitGroup Coordination
gogo
123456789101112131415161718package mainimport ("fmt""sync")func main() {var wg sync.WaitGroupfor i := 1; i <= 3; i++ {wg.Add(1)go func(id int) {defer wg.Done()fmt.Printf("Worker #%d done\n", id)}(i)}wg.Wait() // Block until all 3 workers call Done()fmt.Println("All workers finished.")}
Line-by-Line Technical Breakdown
1Always pass WaitGroup pointers (&wg), never pass WaitGroups by value.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[GO]
GO SOURCE EDITOR
Interactive Live CodeIndustry Best Practices & Professional Standards
- Always run tests with the -race flag enabled in CI pipelines.
Lesson Summary & Core Takeaways
- Sync primitives coordinate parallel tasks and protect shared state.