Go Sync Package: WaitGroup and Mutex Explained

Updated 4 min read
Go Sync Package featured image: cards showing Mutex, WaitGroup and Once

The Go sync package gives you simple tools to keep goroutines from stepping on each other’s data. In this post, you will learn what a data race is and how Mutex, WaitGroup, RWMutex and Once fix real problems. Each idea comes with a short example that you can run yourself.

This lesson builds on the last two. So if goroutines or channels still feel new, first read goroutines in Go for beginners and channels in Go with examples. We will also use pointer receivers from structs and methods in Go.

What Is the Go Sync Package?

The sync package is part of the standard library. In particular, it offers small building blocks for coordinating goroutines, such as locks and counters. You need no install, just import "sync".

For example, think of a single shared bathroom with a lock on the door. Only one person goes in at a time, and everyone else waits. The Go sync package gives your goroutines that same lock, so shared data stays safe.

The Problem the Go Sync Package Solves: Data Races

var wg sync.WaitGroup
count := 0

for i := 0; i < 1000; i++ {
	wg.Add(1)
	go func() {
		defer wg.Done()
		count++
	}()
}
wg.Wait()
fmt.Println(count) // often less than 1000, for example 997

A data race happens when two goroutines change the same variable at the same time. Here count++ reads, adds and writes back in three steps. So two goroutines can read the same old value, and one update gets lost.

Spotting Races with -race

go run -race main.go
# WARNING: DATA RACE

Fortunately, the -race flag turns on Go’s race detector. Then it watches memory while your program runs and reports any unsafe access. Use it in tests, because races often hide on fast machines.

Protecting Data with sync.Mutex

type Counter struct {
	mu    sync.Mutex
	value int
}

func (c *Counter) Inc() {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.value++
}

So a mutex, short for mutual exclusion, lets only one goroutine into a section of code at a time. The diagram below compares the race with the locked version.

Go Sync Package diagram showing a data race losing an update next to a mutex keeping the count correct

Without a lock, two goroutines lose an update. With a mutex, they take turns and the count is correct.

Lock, Unlock and defer

First, Lock() waits until the mutex is free and then takes it. Next, defer Unlock() makes sure the method releases it when it ends. Now 1,000 goroutines calling c.Inc() always give exactly 1000.

Waiting with sync.WaitGroup

var wg sync.WaitGroup
var c Counter

for i := 0; i < 1000; i++ {
	wg.Add(1)
	go func() {
		defer wg.Done()
		c.Inc()
	}()
}
wg.Wait()
fmt.Println(c.value) // 1000

You met WaitGroup in the goroutines lesson. In short, it counts running tasks, while the mutex protects shared data. Together they are the most common pair in the Go sync package.

Other Go Sync Package Tools

sync.RWMutex for Many Readers

type Cache struct {
	mu   sync.RWMutex
	data map[string]string
}

func (c *Cache) Get(key string) string {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.data[key]
}

func (c *Cache) Set(key, value string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.data[key] = value
}

An RWMutex lets many goroutines read at once, but only one write at a time. For instance, this suits caches, where reads happen far more often than writes.

sync.Once for One-Time Setup

var once sync.Once
for i := 0; i < 3; i++ {
	once.Do(func() { fmt.Println("setup runs once") })
}
// setup runs once

Finally, Once runs a function exactly one time, even if many goroutines call it. For example, use it to open a database connection the first time someone needs it.

Mutex or Channel: When to Use the Go Sync Package

SituationBest tool
Protect a shared counter, map or cachesync.Mutex or RWMutex
Pass data or work from one goroutine to anotherChannel
Wait for a group of goroutines to finishsync.WaitGroup
Run setup code only oncesync.Once

As a simple rule, use channels to move data and a mutex to guard data. Both are correct Go, so pick whichever makes the code easier to read.

Common Mistakes with the Go Sync Package

Error you seeWhy it happensHow to fix it
fatal error: sync: unlock of unlocked mutexUnlock ran without a Lock.Pair every Lock with one Unlock.
show passes lock by value (from go vet)A struct with a mutex was copied.Pass a pointer instead.
Program freezesThe code locked twice without unlocking.Use defer mu.Unlock().

Copying a mutex is a quiet bug, since each copy has its own lock. Therefore, run go vet to catch it early. Concurrency questions are interview favourites, so practise with my Go interview questions and answers.

Official Resources

These pages come straight from the Go team, so they are always accurate and up to date.

Quick Recap

  • The Go sync package helps goroutines share data safely.
  • A data race loses updates, and go run -race finds it.
  • Mutex lets one goroutine at a time into a section, with defer Unlock.
  • WaitGroup waits for tasks, RWMutex allows many readers and Once runs setup once.
  • Never copy a struct that holds a mutex.

What’s Next?

You can now run and coordinate goroutines safely. Next, we will learn how to cancel slow work and set deadlines with the context package.

Coming soon: Go Context Explained for Beginners