With goroutines, launching concurrent work takes a single go keyword. After that you still need to know when the work finishes, and you need to keep goroutines that share memory from corrupting each other's state. The sync package covers both. It has a small set of primitives for the most common coordination patterns, with less ceremony than lower-level threading APIs.
The goroutine leak problem
When the main goroutine exits, the Go runtime shuts down the entire program immediately, without cleanup and without waiting. Any goroutines still running are silently terminated. Two things go wrong: work never completes, and resources the goroutines were holding (open files, database connections, locked mutexes) are never released.
A naive workaround is to sleep long enough for goroutines to finish:
package mainimport ( "fmt" "time")func process(id int) { time.Sleep(100 * time.Millisecond) fmt.Printf("job %d done\n", id)}func main() { for i := 0; i < 5; i++ { go process(i) } time.Sleep(200 * time.Millisecond) // hope this is long enough...}This only works by accident. If process takes longer than expected, or scheduling is delayed under load, the main goroutine exits before all jobs complete. A fixed sleep is a guess about timing, so it can't coordinate anything.
WaitGroup
sync.WaitGroup solves the fan-out/fan-in problem directly: it waits for a collection of goroutines to finish before allowing the caller to proceed.
A WaitGroup is an atomic counter with three operations:
| Method | Effect |
|---|---|
Add(n) | Increment the counter by n, called before starting goroutines |
Done() | Decrement the counter by 1, called when a goroutine finishes |
Wait() | Block until the counter reaches zero |
package mainimport ( "fmt" "sync" "time")func process(id int, wg *sync.WaitGroup) { defer wg.Done() time.Sleep(100 * time.Millisecond) fmt.Printf("job %d done\n", id)}func main() { var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go process(i, &wg) } wg.Wait() fmt.Println("all jobs complete")}defer wg.Done() inside process ensures the counter is decremented even if the function returns early or panics. wg.Wait() in main blocks until all five goroutines have called Done, at which point the counter reaches zero and execution continues.
A WaitGroup must not be copied after first use. Pass it to goroutines and helper functions as a pointer (*sync.WaitGroup), never by value.
Data races and shared memory
WaitGroup handles goroutine lifetimes. Once several goroutines run concurrently, you also have to deal with shared state.
Consider a thousand goroutines each incrementing a shared counter:
package mainimport ( "fmt" "sync")func main() { var counter int var wg sync.WaitGroup for i := 0; i < 1000; i++ { wg.Add(1) go func() { defer wg.Done() counter++ // unsafe: read-modify-write is not atomic }() } wg.Wait() fmt.Println(counter) // not necessarily 1000}Running this with go run -race main.go reports a data race. The increment counter++ is not a single CPU instruction. It expands to three steps: read the current value, add one, write the result back. If two goroutines read the same value before either writes back, one increment is lost.
Data races are some of the hardest bugs to catch in concurrent programming. They produce results that look correct most of the time and fail unpredictably under load or on different hardware. Run your tests with -race as a habit; the overhead is worth it.
Mutex
sync.Mutex ensures that only one goroutine can execute a critical section at a time. Any goroutine that calls Lock while another holds the mutex is blocked until Unlock is called.
package mainimport ( "fmt" "sync")func main() { var counter int var mu sync.Mutex var wg sync.WaitGroup for i := 0; i < 1000; i++ { wg.Add(1) go func() { defer wg.Done() mu.Lock() defer mu.Unlock() counter++ }() } wg.Wait() fmt.Println(counter) // always 1000}The convention is to call defer mu.Unlock() immediately after mu.Lock(). The lock is then released when the surrounding function returns, whichever code path it takes. Without defer it's easy to forget an Unlock in one of the branches.
The code between Lock and Unlock is the critical section: the block that requires exclusive access to shared state. Only one goroutine runs it at a time; all others wait at Lock.
Critical sections and performance
Every line inside a critical section is serial. Goroutines waiting at Lock make no progress until the current holder calls Unlock. Slow operations inside the critical section limit how much of the program can run in parallel.
So keep the critical section small: lock only what must be protected, do any expensive work outside the lock, and release as soon as the shared state is stable.
For workloads with many more reads than writes, even a minimal mutex creates unnecessary contention: readers that don't modify the data still block each other, even though they could safely run in parallel. RWMutex exists for this case.
RWMutex
sync.RWMutex is a reader/writer lock. It distinguishes between two modes of access:
- Read lock (
RLock/RUnlock): multiple goroutines may hold a read lock simultaneously. Readers do not block each other. - Write lock (
Lock/Unlock): exclusive. A writer waits for all active readers to finish, and new readers wait while a writer holds the lock.
A shared in-memory cache fits this pattern, since lookups are frequent and updates are rare:
package mainimport ( "fmt" "sync")type Cache struct { mu sync.RWMutex items map[string]string}func (c *Cache) Get(key string) (string, bool) { c.mu.RLock() defer c.mu.RUnlock() v, ok := c.items[key] return v, ok}func (c *Cache) Set(key, value string) { c.mu.Lock() defer c.mu.Unlock() c.items[key] = value}func main() { cache := &Cache{items: make(map[string]string)} cache.Set("lang", "Go") var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() v, _ := cache.Get("lang") fmt.Println(v) }() } wg.Wait()}All ten reader goroutines proceed without blocking each other. A concurrent Set would wait until active readers release their read locks, and new readers that arrive while a writer is waiting get queued behind it, so the writer isn't starved indefinitely.
What this means in practice
WaitGroup, Mutex, and RWMutex address the two core challenges in concurrent programs: lifetime (knowing when goroutines finish) and safety (preventing concurrent writes from corrupting shared state).
WaitGroup gives you structured fan-out/fan-in. Mutex serializes access to shared data, and RWMutex relaxes that serialization to allow parallel reads where writes are infrequent. You'll find these three in nearly every non-trivial concurrent Go program.