38. Sharing data safely
In Chapter 37, every variable had one owner. Other goroutines sent it values over a channel, and only the owner changed it. That rule kept everything safe, but it is not always convenient. A web server, for example, keeps one list of visitors, and every request wants to add to it.
This chapter shows what goes wrong when several goroutines change the same variable, how to find the problem, and how to fix it with a mutex. It ends with a worker pool, which runs many jobs with only a few goroutines.
Lost updates
Here ten goroutines each add 1 to the same counter, a hundred
thousand times. The answer should be one million. This is
exercises/38/01-lost-updates.go:
func main() {
count := 0
var wg sync.WaitGroup
for range 10 {
wg.Go(func() {
for range 100000 {
count = count + 1
}
})
}
wg.Wait()
fmt.Println("Expected: 1000000")
fmt.Println("Got: ", count)
}One run printed:
Expected: 1000000
Got: 418273
Run it again, and you get a different wrong number. Now and then it may even come out close to the right answer. That is worse, not better: a program that is only sometimes wrong is hard to catch.
Where did the missing additions go? count = count + 1
looks like one step, but the computer does it in three:
read count, add 1,
write the result back. Two goroutines can do those
steps at the same time:
| Goroutine A | Goroutine B | count |
|---|---|---|
| reads 10 | 10 | |
| reads 10 | 10 | |
| writes 11 | 11 | |
| writes 11 | 11 |
Both added 1, but count went up by only one. One
addition is lost. This is called a lost update, and it
happens many thousands of times in a run like the one above.
When two goroutines touch the same variable at the same time, and at least one of them changes it, that is a data race. A data race is always a bug, even when the output happens to look right.
The race detector
Go has a tool that finds data races for you: the race
detector. Add -race to go run:
go run -race exercises/38/01-lost-updates.go
The program runs more slowly, and Go watches every read and write. When two goroutines touch the same memory without protection, it prints a report. It is long, but the start looks something like this:
==================
WARNING: DATA RACE
Read at 0x00c000012108 by goroutine 8:
main.main.func1()
C:/go-work/exercises/38/01-lost-updates.go:20 +0x84
...
Previous write at 0x00c000012108 by goroutine 7:
main.main.func1()
C:/go-work/exercises/38/01-lost-updates.go:20 +0x96
...
and the end:
Found 1 data race(s)
exit status 66
WARNING: DATA RACE says what was found. The lines below
it say where: two different goroutines used the same memory, both at
line 20, the count = count + 1 line.
main.main.func1 is Go's name for the first function literal
inside main.
The detector only finds races that actually happen while it watches, so run the program the way it is really used. If it reports nothing, that is good news, but not a proof.
On Windows, -race needs a C compiler, such as gcc from
MinGW-w64, and the Go installer from Chapter 06 does not include one.
Without it, Go stops with an error that mentions cgo
instead of running the program. You do not need the detector to follow
this chapter: the rules below keep your programs free of races. If you
have a Linux or macOS computer, or install a C compiler later, try it
there.
sync.Mutex: one at a
time
The fix is to make sure only one goroutine at a time can do the read,
add and write. A mutex (short for mutual
exclusion) is a lock for this. sync.Mutex has two
methods:
mu.Lock()takes the lock. If another goroutine holds it,Lockwaits until it is free.mu.Unlock()gives the lock back, so that a waiting goroutine can take it.
The code between Lock and Unlock can
therefore only run in one goroutine at a time. This is
exercises/38/02-mutex-counter.go:
func main() {
// mu protects count. Any code that reads or changes count must hold mu.
var mu sync.Mutex
count := 0
var wg sync.WaitGroup
for range 10 {
wg.Go(func() {
for range 100000 {
mu.Lock()
count = count + 1
mu.Unlock()
}
})
}
wg.Wait()
fmt.Println("Expected: 1000000")
fmt.Println("Got: ", count)
}Output, on every run:
Expected: 1000000
Got: 1000000
Like a sync.WaitGroup, a sync.Mutex is
ready to use as soon as it is declared. Its zero value is an unlocked
mutex.
Look at the comment above mu. A mutex does not know what
it protects. Nothing in Go connects mu to
count. It works only because every piece
of code that touches count takes mu first. One
line that changes count without the lock, and the race is
back. The comment tells the next reader the rule.
The final fmt.Println reads count without
the lock. That is safe, because it runs after wg.Wait(),
when every goroutine has finished, and nobody else can touch
count any more.
Open exercises/38/02-mutex-counter.go and move
mu.Lock() and mu.Unlock() so that they are
around the whole inner for loop instead of the one line. Is
the answer still right? Is it slower or faster? (It is right, and
usually faster, because each goroutine locks once instead of 100,000
times. But now the goroutines take turns, and nothing runs at the same
time. A real program keeps the locked part small.)
A map shared without a lock
With a counter, a data race gives wrong numbers. With a map, Go
notices and stops the whole program. This is
exercises/38/03-map-crash.go:
func main() {
counts := map[string]int{}
var wg sync.WaitGroup
for range 2 {
wg.Go(func() {
for range 100000 {
counts["apple"] = counts["apple"] + 1
}
})
}
wg.Wait()
fmt.Println(counts["apple"])
}It almost always stops with:
fatal error: concurrent map writes
followed by a long list of goroutines. Sometimes the message is
fatal error: concurrent map read and map write instead,
because the line also reads the map. A map keeps its data in a careful
internal layout, and two goroutines changing it at once could break that
layout. Go checks for this, and stops rather than carry on with a broken
map.
This is not a panic you can catch or ignore. It ends the program at once. In a web server, it would take down the whole site, for every visitor, because two requests arrived together. Every map that several goroutines change needs a mutex.
A mutex in a struct
In a real program, the mutex lives next to the data it protects, in
the same struct, and the struct's methods do the locking. Code outside
the struct never touches the lock or the data. It calls the methods.
This is exercises/38/04-tally.go:
// tally counts words. Make one with newTally. It is safe to use from many
// goroutines at once.
type tally struct {
mu sync.Mutex // mu protects counts
counts map[string]int // word -> how many times it was seen
}
func newTally() *tally {
return &tally{counts: map[string]int{}}
}
// add counts one more of word.
func (t *tally) add(word string) {
t.mu.Lock()
defer t.mu.Unlock()
t.counts[word] = t.counts[word] + 1
}
// count returns how many times word was seen.
func (t *tally) count(word string) int {
t.mu.Lock()
defer t.mu.Unlock()
return t.counts[word]
}
// snapshot returns a copy of all the counts. The caller can use the copy for
// as long as it likes, without the lock.
func (t *tally) snapshot() map[string]int {
t.mu.Lock()
defer t.mu.Unlock()
return maps.Clone(t.counts)
}main starts one goroutine per line of text. Each one
splits its line into words and calls words.add for each
word:
words := newTally()
var wg sync.WaitGroup
for _, line := range lines {
wg.Go(func() {
for _, w := range strings.Fields(line) {
words.add(w)
}
})
}
wg.Wait()
fmt.Println("the:", words.count("the"))It then sorts the keys of the snapshot and prints them. Output:
the: 4
a 2
and 1
cat 2
dog 2
log 1
mat 1
on 2
sat 2
the 4
The goroutines run in any order, but the counts are the same every time. This is the shape Chapter 30 taught for a small type, with one addition: the lock.
- The mutex is a field, next to the data, with a comment that says what it protects. Anyone reading the struct sees the rule.
- Every method starts with
t.mu.Lock()anddefer t.mu.Unlock().defer, from Chapter 31, gives the lock back on every way out of the method. Without it, one earlyreturnthat forgetsUnlockleaves the mutex locked forever, and the nextLockwaits forever. - The methods have pointer receivers,
(t *tally). With a value receiver, each call would get a copy of the struct, and with it a copy of the mutex. Each call would lock its own copy, which protects nothing.go vetcatches this, with a message that says the methodpasses lock by value. For the same reason,newTallyreturns a pointer, and the program passes that pointer around, never a copy of the struct. - Reading takes the lock too.
countonly reads the map, but a read at the same time as another goroutine's write is still a data race, as the map crash showed. snapshotreturns a copy.maps.Clone, from themapspackage, makes a new map with the same keys and values. Ifsnapshotreturnedt.countsitself, the caller would hold the real map with no lock, and could read it while another goroutine adds to it. The copy belongs to the caller alone. For a slice,slices.Clonedoes the same job.
A method that holds the lock must not call another method that locks
the same mutex. If add called t.count(word),
count would wait for add to give the lock
back, and add would wait for count to return.
Both wait forever. Go's mutex does not allow one goroutine to lock it
twice. Keep the locked methods small, and have them use the fields
directly.
Open exercises/38/04-tally.go and add a method
total() int that returns the number of words counted, by
adding up the values in the map. Lock it like the others, and print the
total at the end of main. There are 17 words.
Or do not share at all
There is another way to solve the same problem, the one Chapter 37
used: give the map to one goroutine, and have the
others send it words over a channel. Only the owner ever touches the
map, so there is nothing to lock. This is
exercises/38/05-owner.go:
// countWords is the owner. It reads words until the channel is closed, then
// sends the finished map on result.
func countWords(words <-chan string, result chan<- map[string]int) {
counts := map[string]int{}
for w := range words {
counts[w] = counts[w] + 1
}
result <- counts
}
func main() {
lines := []string{
"the cat sat on the mat",
"the dog sat on the log",
"a cat and a dog",
}
words := make(chan string)
result := make(chan map[string]int)
go countWords(words, result)
var wg sync.WaitGroup
for _, line := range lines {
wg.Go(func() {
for _, w := range strings.Fields(line) {
words <- w
}
})
}
wg.Wait()
close(words)
counts := <-resultThe output is the same table as before. main waits for
the senders, closes words so that the owner's
for range ends, and then receives the finished map. Once
the owner has sent the map, it no longer touches it, so
main can use it freely.
Which way is better? Both are correct. A rough guide:
- Use a mutex when several goroutines need to read and change some data whenever they like, such as a web server's list of messages. A struct with a mutex and small methods is short and clear.
- Use an owner goroutine and channels when the work flows in one direction: many goroutines produce values, and one collects them.
A worker pool
Chapter 36 started one goroutine per job. That is fine for three downloads. But what about ten thousand files? Ten thousand goroutines are no problem for Go itself, but ten thousand files open at the same moment can be too many for the operating system, and a disk or a web server can only do so much at once.
A worker pool solves this. A fixed number of
goroutines, the workers, take jobs from one channel,
one at a time, and send results on another. With three workers, no more
than three jobs run at once, however many jobs there are. This is
exercises/38/06-worker-pool.go:
// result is what a worker sends back for one job.
type result struct {
job int
square int
worker int
}
// worker takes jobs until the jobs channel is closed and empty.
func worker(id int, jobs <-chan int, results chan<- result) {
for n := range jobs {
time.Sleep(100 * time.Millisecond) // pretend this is slow work
results <- result{job: n, square: n * n, worker: id}
}
}
func main() {
start := time.Now()
jobs := make(chan int)
results := make(chan result)
// Start the workers.
var wg sync.WaitGroup
for id := 1; id <= 3; id++ {
wg.Go(func() {
worker(id, jobs, results)
})
}
// Send the jobs, then close the channel so the workers know there are no
// more. This runs in its own goroutine, so main can read results meanwhile.
go func() {
for n := 1; n <= 8; n++ {
jobs <- n
}
close(jobs)
}()
// Close results once every worker has finished.
go func() {
wg.Wait()
close(results)
}()
total := 0
for r := range results {
fmt.Printf("worker %d: %d squared is %d\n", r.worker, r.job, r.square)
total = total + r.square
}
fmt.Println("Sum of the squares:", total)
fmt.Println("Took about", time.Since(start).Round(100*time.Millisecond))
}One run printed:
worker 3: 1 squared is 1
worker 1: 3 squared is 9
worker 2: 2 squared is 4
worker 2: 4 squared is 16
worker 3: 5 squared is 25
worker 1: 6 squared is 36
worker 1: 7 squared is 49
worker 3: 8 squared is 64
Sum of the squares: 204
Took about 300ms
Which worker gets which job changes from run to run, and so does the order of the lines. The sum is always 204. Eight jobs of 100 milliseconds, three at a time, take three rounds: about 300 milliseconds. One after another, they would take 800.
There are four kinds of goroutine here, and each has one job:
- Three workers. Each one loops over
jobswithfor range. Whichever worker is free takes the next job. Whenjobsis closed and empty, the loop ends, and the worker returns. - One sender. It sends the eight jobs, then closes
jobs. It is a goroutine of its own because each send waits for a free worker, and a worker waits formainto take its result. Ifmainsent all the jobs itself before reading any results, everyone would be waiting for everyone else: a deadlock. - One closer. It waits for the workers with the
WaitGroup, then closes
results. This is the "wait, then close" pattern from Chapter 37. main, which ranges overresultsuntil it is closed, and adds up the total.
Notice that total is only changed by main,
so it needs no mutex. The workers send values, and do not share any
variable. If the workers did need to update shared data, such as a word
count, they would call the methods of a struct with a mutex, like the
tally above.
The number of workers is the knob. One worker does the jobs one after another. A hundred workers for eight jobs is the same as one goroutine per job. Somewhere between is a number that keeps the computer busy without swamping it. For work that reads files, a few workers per core is a good start. The Duplicate Finder at the end of this part lets you choose with a flag.
Open exercises/38/06-worker-pool.go. Change the number
of workers to 1, then to 8, and compare the times. Then change it back
to 3, and send 20 jobs instead of 8. How long do you expect it to
take?
Homework
Homework starters are in exercises/38/homework/. Run
them all from the go-work folder. Each one runs as it is,
but Problem 1 gives a wrong answer until you fix it.
Problem 1 — Fix the balance
Open exercises/38/homework/01-fix-the-balance.go. Four
goroutines pay in 1, a hundred thousand times each, and four take out 1
the same number of times, so the balance should end at 1000. Run it: it
does not. Protect balance with a sync.Mutex,
so that it prints Balance: 1000 every time.
Problem 2 — A guest list
Open exercises/38/homework/02-guest-list.go. Write the
guestList type: a struct with a sync.Mutex and
a slice of names, and three methods with pointer receivers,
add, size and sorted. Each one
locks the mutex and unlocks it with defer.
sorted returns a sorted copy, and leaves the list itself
alone. main is finished.
Problem 3 — A pool of four
Open exercises/38/homework/03-slow-lengths.go. Measuring
ten words one after another takes two seconds. Use a worker pool of four
workers instead, and print the words with their lengths in the original
order. It should take about 600 milliseconds. Send each job with its
index in the slice, and send the index back with the result.
Challenge — Counting words with a pool
Open exercises/38/homework/04-word-count-pool.go. Count
every word in five short documents with a pool of three workers, which
all add to one shared tally: a struct with a mutex and a map. Lower each
word with strings.ToLower. Then print the five most common
words, most common first, with words that have the same count in
alphabetical order.
Stuck or finished? Open the homework solutions page.