38. Sharing data safely — Homework solutions

The .go solution files are in exercises/38/homework/solutions/. Run each one from the go-work folder. Where a program prints from several goroutines, or measures time, the output shown is one possible run.

Problem 1 — Fix the balance

Problem. Eight goroutines change one balance. Stop the lost updates.

How to think about it. Run the starter first. It prints a different wrong balance each time, such as Balance: 1734 or Balance: -2210, because payments in and out are lost. This is the counter from the chapter, twice. Add a sync.Mutex next to balance, with a comment that says what it protects, and put mu.Lock() and mu.Unlock() around both changes. Locking only the additions is not enough: a subtraction without the lock can still overlap with an addition.

Worked solution.

package main

import (
    "fmt"
    "sync"
)

func main() {
    // mu protects balance.
    var mu sync.Mutex
    balance := 1000

    var wg sync.WaitGroup
    for range 4 {
        wg.Go(func() {
            for range 100000 {
                mu.Lock()
                balance = balance + 1
                mu.Unlock()
            }
        })
        wg.Go(func() {
            for range 100000 {
                mu.Lock()
                balance = balance - 1
                mu.Unlock()
            }
        })
    }
    wg.Wait()

    fmt.Println("Balance:", balance)
}

Output, on every run:

Balance: 1000

There is no defer here, because the locked part is one line inside a loop, not a whole function. defer would only run when the function literal returns, after all 100,000 rounds, so the second Lock in the loop would wait forever.

Common mistakes.

  • Making two mutexes, one for the additions and one for the subtractions. Each lock only keeps out goroutines that use the same mutex, so an addition and a subtraction can still overlap. One piece of data, one mutex.
  • Declaring the mutex inside the function literal. Each goroutine then has its own mutex, and nobody ever waits for anybody.

Problem 2 — A guest list

Problem. A type that keeps a list of names, safe to use from several goroutines.

How to think about it. This is the tally from the chapter, with a slice in place of the map. The struct gets two fields: the mutex, with its comment, and the slice. Every method starts with the same two lines, g.mu.Lock() and defer g.mu.Unlock(), even size, which only reads. sorted must not sort g.names itself and return it: the caller would then hold the real slice, without the lock. It copies the slice with slices.Clone, which does for a slice what maps.Clone did for the map, and sorts the copy.

Worked solution.

// guestList holds names. Make one with newGuestList.
type guestList struct {
    mu    sync.Mutex // mu protects names
    names []string
}

func newGuestList() *guestList {
    return &guestList{}
}

func (g *guestList) add(name string) {
    g.mu.Lock()
    defer g.mu.Unlock()

    g.names = append(g.names, name)
}

func (g *guestList) size() int {
    g.mu.Lock()
    defer g.mu.Unlock()

    return len(g.names)
}

func (g *guestList) sorted() []string {
    g.mu.Lock()
    defer g.mu.Unlock()

    names := slices.Clone(g.names)
    slices.Sort(names)
    return names
}

Output:

Guests: 9
Ana, Arif, Budi, Joko, Keiko, Maya, Rina, Sari, Tom

The tables add their guests in a different order on each run, but the sorted list is always the same. newGuestList does not need to make the slice: a nil slice has length 0, and append works on it.

Common mistakes.

  • Value receivers, such as func (g guestList) add(name string). Each call gets a copy of the struct, with its own copy of the mutex and of the slice header. The names are added to the copy and lost, so Guests: 0, and go vet warns that add passes lock by value.
  • Leaving out the lock in size, because it "only reads". A read while another goroutine appends is still a data race.
  • Writing names := g.names and sorting that. It is not a copy: both share the same items underneath, so the real list gets sorted, and the caller can see later changes.

Problem 3 — A pool of four

Problem. Measure ten words with four workers, and keep the original order.

How to think about it. Copy the shape of exercises/38/06-worker-pool.go: workers, a sender, a closer, and main reading results. Results come back in the order they finish, not the order the words are in, so each job carries its index, and each result carries it back. Two small structs, job and result, hold the pairs. main is the only goroutine that writes into lengths, and it writes each length at its index. This is the "one slot each" idea from Chapter 36, with a pool doing the work.

Worked solution.

// job is one word, with its place in the slice.
type job struct {
    index int
    word  string
}

// result is the length of the word at index.
type result struct {
    index  int
    length int
}

func worker(jobs <-chan job, results chan<- result) {
    for j := range jobs {
        results <- result{index: j.index, length: measure(j.word)}
    }
}

and in main, in place of the old loop:

jobs := make(chan job)
results := make(chan result)

var wg sync.WaitGroup
for range 4 {
    wg.Go(func() {
        worker(jobs, results)
    })
}

go func() {
    for i, w := range words {
        jobs <- job{index: i, word: w}
    }
    close(jobs)
}()

go func() {
    wg.Wait()
    close(results)
}()

for r := range results {
    lengths[r.index] = r.length
}

Output:

goroutine  9
channel    7
mutex      5
worker     6
pool       4
select     6
context    7
deadline   8
ticker     6
signal     6
Took about 600ms

Ten jobs, four at a time, take three rounds of 200 milliseconds: four, four, then two.

Common mistakes.

  • Writing wg.Wait() and close(results) in main, before the for range results loop. The workers wait to send results that nobody is reading yet, and main waits for the workers: a deadlock.
  • Forgetting close(jobs). The workers' for range loops never end, so wg.Wait() never returns, results is never closed, and the program stops with the deadlock error.
  • Appending each result to a slice as it arrives. The lengths then come out in the order the jobs finished, which changes from run to run.

Challenge — Counting words with a pool

Problem. Three workers count the words of five documents into one shared tally, then print the top five.

How to think about it. Two pieces from the chapter fit together. The tally is the struct from exercises/38/04-tally.go, with only add and snapshot. The pool is the one from exercises/38/06-worker-pool.go, but simpler: a worker does not send results back, it calls words.add, and the mutex inside the tally keeps the map safe. With no results channel, nothing waits on main, so main can send the documents itself, close jobs, and call wg.Wait().

For the top five, turn the snapshot into a slice of rows and sort it with slices.SortFunc, as in Chapter 28: a higher count goes first, and for equal counts strings.Compare puts the words in alphabetical order.

Worked solution.

// tally counts words. It is safe to use from many goroutines at once.
type tally struct {
    mu     sync.Mutex // mu protects counts
    counts map[string]int
}

func newTally() *tally {
    return &tally{counts: map[string]int{}}
}

func (t *tally) add(word string) {
    t.mu.Lock()
    defer t.mu.Unlock()

    t.counts[word] = t.counts[word] + 1
}

func (t *tally) snapshot() map[string]int {
    t.mu.Lock()
    defer t.mu.Unlock()

    return maps.Clone(t.counts)
}

func worker(documents <-chan string, words *tally) {
    for doc := range documents {
        for _, w := range strings.Fields(doc) {
            words.add(strings.ToLower(w))
        }
    }
}

// wordCount is one row of the result.
type wordCount struct {
    word  string
    count int
}

// mostFirst puts the higher count first, and equal counts in word order.
func mostFirst(a wordCount, b wordCount) int {
    if a.count != b.count {
        return b.count - a.count
    }
    return strings.Compare(a.word, b.word)
}

and in main:

words := newTally()
jobs := make(chan string)

var wg sync.WaitGroup
for range 3 {
    wg.Go(func() {
        worker(jobs, words)
    })
}

for _, doc := range documents {
    jobs <- doc
}
close(jobs)
wg.Wait()

rows := []wordCount{}
for w, n := range words.snapshot() {
    rows = append(rows, wordCount{word: w, count: n})
}
slices.SortFunc(rows, mostFirst)

for _, row := range rows[:5] {
    fmt.Printf("%-5s %d\n", row.word, row.count)
}

Output:

the   7
a     3
cat   3
dog   3
on    3

the appears seven times once The is lowered. Four words appear three times, and the tie-break puts them in alphabetical order, so the output is the same on every run. worker takes a *tally, a pointer, so that all three workers add to the same tally.

Common mistakes.

  • Giving worker a tally instead of a *tally. Each worker then gets a copy with its own mutex. (The copied map still points to the same data underneath, so the mutexes no longer protect it, and the program can crash with concurrent map writes.)
  • Forgetting strings.ToLower. The and the are then counted as two different words, The 4 and the 3.
  • Sorting with b.count - a.count alone. Words with equal counts then come out in a different order from run to run, because a map has no order.
  • Slicing rows[:5] when there could be fewer than five words. It is safe here, but for any text, check len(rows) first.

Done?

You can now spot a data race, protect shared data with a mutex inside a struct, and spread work over a fixed number of workers. One question is left: how do you stop goroutines that are taking too long, or when the user has had enough? The next chapter, select, timeouts and context, answers it.