QUICK START:HTMLCSSJavaScriptTypeScriptPythonSQLReactNext.jsNode.jsDSASystem DesignDevOpsCybersecurityAI / ML
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

go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
for 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 Code

Industry 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.