Mutex & the sync package — Go

A race condition happens when two or more goroutines touch the same data, at least one writes, with no synchronisation; sold++ is read, add, write, so updates…

On the till at Bimo's Meatball Stall there is one sales book, and two waiters writing in it. Both read "41 portions" at the same moment, then each writes "42". Two portions were sold, but the book only went up by one.

The fix: there is only one pen. Whoever holds the pen may read and write, the other waits until the pen is handed back. In Go, that pen is a mutex (mutual exclusion): a lock that makes sure only one goroutine touches shared data at a time.

Race condition: lost sales

In the program below, 100 goroutines each call record() 10 times, and record() holds just sold++. Guess: is the result always sold: 1000?

package main

import (
	"fmt"
	"sync"
)

var sold int

func record() {
	sold++
}

func main() {
	var wg sync.WaitGroup
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < 10; j++ {
				record()
			}
		}()
	}
	wg.Wait()
	fmt.Println("sold:", sold)
}

This program was run 18 times on the Go Playground (8 CPUs). 14 times it printed sold: 1000, but four times it printed sold: 950, sold: 990, sold: 990 and sold: 970. So it is not always 1000.

Why? sold++ looks like one step, but it is three: read the value, add one, write it back. Two goroutines can overtake each other in the middle:

Step Goroutine A Goroutine B sold
1 read: 41 41
2 read: 41 41
3 write 42 42
4 write 42 42

Two sales, but the count only went up by one. This is called a race condition: two or more goroutines touch the same variable, at least one of them writes, with no synchronisation. The bug only appears when the schedule happens to overtake, so sometimes it shows and sometimes it doesn't. That is what makes a race hard to find.

sync.Mutex: one goroutine at a time

var (
	sold int
	mu   sync.Mutex
)

func record() {
	mu.Lock()
	defer mu.Unlock()
	sold++
}

Now B, arriving while A holds the lock, has to wait, then reads 42, not 41. The result is always sold: 1000.

In the exercise: a safe counter

This lesson's exercise uses the same pattern under other names: a variable counter, a mutex mu, and a function increment(). main already runs 100 goroutines that each call increment() 10 times, then prints Counter: 1000. Your job is to fill increment() with mu.Lock(), defer mu.Unlock() and counter++.

sync.RWMutex: many readers, one writer

When data is read often but changed rarely, such as a price list, sync.RWMutex fits better:

var (
	prices = map[string]int{"tendon meatballs": 15, "chicken noodles": 12, "iced tea": 5}
	pmu    sync.RWMutex
)

func getPrice(menu string) int {
	pmu.RLock()
	defer pmu.RUnlock()
	return prices[menu]
}

func setPrice(menu string, newPrice int) {
	pmu.Lock()
	defer pmu.Unlock()
	prices[menu] = newPrice
}

RLock can be held by many readers at once. Lock stays exclusive: the writer waits for every reader to finish, and new readers wait for the writer. When writes are as frequent as reads, a plain sync.Mutex is simpler and often faster.

For a single number, like sold, there is a shorter way: the sync/atomic package. Add does the read, the add and the write as one step that no other goroutine can interrupt:

var sold atomic.Int64

func record() {
	sold.Add(1)
}

With the same main and fmt.Println("sold:", sold.Load()) at the end, the result is always sold: 1000. Other options:

Tool When to pick it
atomic.Int64 One number that is only added to and read, like a counter.
sync.Mutex Several pieces of data that change together, or a check then a change. The default in this lesson because it can protect anything.
sync.RWMutex Data that is read often and changed rarely.
Channel Handing work or results to another goroutine, instead of sharing a variable.

💡 Finding races with -race

Go has a race detector: go run -race stall.go. When there is a race, the program prints a report that starts with WARNING: DATA RACE, names the read and the write that collided with their goroutines and lines of code, and exits with exit status 66. Run your tests with go test -race too. Maps are stricter still: writing a map from many goroutines without a lock can kill the program straight away with fatal error: concurrent map writes.

⚠️ Locks that jam or protect nothing

TL;DR: A race condition happens when two or more goroutines touch the same data, at least one writes, with no synchronisation; sold++ is read, add, write, so updates can be lost (on the Go Playground: 950 out of 1000). sync.Mutex lets only one goroutine into the critical section: mu.Lock(), defer mu.Unlock(), then change the data. Use sync.RWMutex (RLock to read, Lock to write) when data is read a lot and written rarely. Find races with go run -race. Don't Lock twice, don't Unlock without Lock, and don't copy a mutex.

⚡ Lost sales

Guess first: 100 goroutines each call record() 10 times, and record() holds just sold++. Is the result always sold: 1000?

Not always. On the Go Playground it once printed sold: 950. sold++ is three steps: read, add one, write back. Two goroutines can both read 41, then both write 42.

Meaning: That is a race condition: two or more goroutines touch the same variable, at least one of them writes, with no synchronisation.

⚡ One pen, one goroutine

Write:

func record() {
	mu.Lock()
	defer mu.Unlock()
	sold++
}

Meaning: mu.Lock() takes the lock, and any other goroutine waits on that line. defer mu.Unlock() releases it when the function ends, a panic included. The result is always sold: 1000.

⚡ Many readers, one writer

Write:

pmu.RLock()
defer pmu.RUnlock()
return prices[menu]

Meaning: sync.RWMutex fits data that is read often but changed rarely. RLock can be held by many readers at once, Lock stays exclusive for a writer.

What you will learn