36. Goroutines

Every program so far has done one thing at a time. The To-do Tool reads its file, changes one task, and writes the file back, and that is the right way for it to work. But some jobs spend most of their time waiting: for a file to be read, for a web page to answer, for a slow calculation to finish. Doing those one after another wastes the waiting time.

Part 8 is about doing several things at the same time. This chapter starts them with goroutines. Chapter 37 lets them hand results to each other with channels. Chapter 38 shows how to share data between them safely, and Chapter 39 how to stop them with timeouts and Ctrl+C. The part ends with a Duplicate Finder, a tool that looks through a folder for identical files and checks several files at once.

One thing after another

Here is a program with three slow jobs, exercises/36/01-one-after-another.go. Each download pretends to fetch a file. It does not really fetch anything: time.Sleep stands in for the half second of waiting that a real download would have.

// Chapter 36 example: three slow jobs, one after another.
// Run with: go run exercises/36/01-one-after-another.go

package main

import (
    "fmt"
    "time"
)

// download pretends to fetch a file. time.Sleep stands in for the waiting.
func download(name string) {
    fmt.Println("Start", name)
    time.Sleep(500 * time.Millisecond)
    fmt.Println("Done ", name)
}

func main() {
    start := time.Now()

    download("a.txt")
    download("b.txt")
    download("c.txt")

    fmt.Println("Took", time.Since(start).Round(100*time.Millisecond))
}

Output:

Start a.txt
Done  a.txt
Start b.txt
Done  b.txt
Start c.txt
Done  c.txt
Took 1.5s

time.Since(start) measures the time, as in Chapter 35. .Round(100*time.Millisecond) rounds the duration to the nearest tenth of a second, so that it prints 1.5s instead of something like 1.502113s.

Three jobs of half a second each take one and a half seconds. While the program waits for a.txt, it does nothing else at all, although b.txt and c.txt could already be on their way.

What "at the same time" means

Your computer has several cores: parts of the processor that can each run code. It can really do several things in the same moment. And even one core can keep several jobs going, by switching to another job whenever the current one has to wait.

Go handles both for you. You tell it which jobs may run at the same time, and Go decides which one runs on which core, and when. This is called concurrency: several jobs in progress at once, instead of one after the other.

go: start a goroutine

A goroutine is a function call that runs at the same time as the rest of the program. To start one, put the word go in front of the call:

go count("goroutine")

The call starts, and the line returns at once, without waiting for count to finish. The next line of main runs while count is still going.

main is a goroutine too: the first one, which Go starts for you. Here are main and one more goroutine, both counting, in exercises/36/03-two-at-once.go:

func count(name string) {
    for i := 1; i <= 3; i++ {
        fmt.Println(name, i)
        time.Sleep(100 * time.Millisecond)
    }
}

func main() {
    go count("goroutine")
    count("main")
}

One run printed:

main 1
goroutine 1
goroutine 2
main 2
goroutine 3
main 3

Run it a few times, and the order changes. Both goroutines print and then sleep for a tenth of a second, so they wake up at almost the same moment, and either one can be first. The order in which goroutines run is not fixed. Every output in this part of the book that comes from several goroutines is one possible run. Yours may be in a different order.

When main returns, everything stops

Take away the second count, and main has nothing left to do. This is exercises/36/02-main-ends.go:

func main() {
    go count("goroutine")
    fmt.Println("main is done")
}

Output:

main is done

The goroutine never got to print. When main returns, the program ends, and any goroutines still running are stopped on the spot. Nobody waits for them. (Now and then, goroutine 1 sneaks in before the end. That is luck, not something to rely on.)

You could put a time.Sleep(time.Second) at the end of main, and the goroutine would usually finish. But that is a guess. Too short, and work is lost. Too long, and the program waits for nothing. What you need is a way to wait exactly until the goroutines are done.

Waiting with sync.WaitGroup

A sync.WaitGroup from the sync package keeps count of goroutines that are still running, and lets you wait until that count is zero. This is exercises/36/04-waitgroup.go:

// Chapter 36 example: wait for goroutines with a sync.WaitGroup.
// Run with: go run exercises/36/04-waitgroup.go

package main

import (
    "fmt"
    "sync"
)

func greet(name string) {
    fmt.Println("Hello,", name)
}

func main() {
    var wg sync.WaitGroup

    wg.Go(func() {
        greet("Ana")
    })
    wg.Go(func() {
        greet("Budi")
    })
    wg.Go(func() {
        greet("Citra")
    })

    wg.Wait()
    fmt.Println("All done")

    // Try this: run the program several times and watch the order of the
    // names. Then add a fourth greeting.
}

One run printed:

Hello, Citra
Hello, Ana
Hello, Budi
All done

The three names can come in any order, but All done is always last. Step by step:

  • var wg sync.WaitGroup makes a WaitGroup. Its zero value, a count of zero, is ready to use.
  • wg.Go(f) starts the function f in a new goroutine, and adds one to the count. When f returns, the count goes down by one.
  • wg.Wait() blocks until the count is zero. To block means to stop at that line and wait. Here, main waits until all three greetings are done.

wg.Go was added in Go 1.25. If go run says wg.Go undefined, your Go is older: install a newer one, as in Chapter 06.

Open exercises/36/04-waitgroup.go and run it several times. Does the order of the names change? Add a fourth greeting, and check that All done still comes last.

A function with no name

wg.Go wants a function that takes nothing and returns nothing. greet takes a name, so it does not fit. The code wraps the call in a function literal: a function with no name, written right where it is used.

func() {
    greet("Ana")
}

It is the same as a function you would write at the top of the file, without the name. Chapter 24 handed a named function to slices.SortFunc. A function literal is handed over in the same way, but is written on the spot. The test functions passed to t.Run in Chapter 34 were function literals too.

A function literal can use the variables around it. In the next example the literal uses name, the loop variable, which was never passed to it as an argument.

Three downloads at once

Now the downloads from the start of the chapter, at the same time. This is exercises/36/05-at-the-same-time.go:

func main() {
    start := time.Now()

    var wg sync.WaitGroup
    files := []string{"a.txt", "b.txt", "c.txt"}
    for _, name := range files {
        wg.Go(func() {
            download(name)
        })
    }
    wg.Wait()

    fmt.Println("Took", time.Since(start).Round(100*time.Millisecond))
}

One run printed:

Start c.txt
Start b.txt
Start a.txt
Done  a.txt
Done  c.txt
Done  b.txt
Took 500ms

All three start, all three wait at the same time, and all three finish together. The whole thing takes about as long as one download, not three. With ten files it would still take about half a second. That is the reason to use goroutines: when the jobs spend their time waiting, they can all wait together.

Each pass of the loop gets its own name variable, so each function literal sees its own file name. This has been true since Go 1.22. Older Go shared one variable across the whole loop, and every goroutine could end up with the last name. You may see old code that works around this with a line such as name := name inside the loop. With Go 1.22 or newer, that line is not needed.

Open exercises/36/05-at-the-same-time.go. Add more names to files, up to ten. How long does it take now? Then replace the wg.Go(...) call in the loop with a plain download(name), and compare.

The older form: Add and Done

Before Go 1.25 there was no wg.Go, and you will see the older form in a lot of code. It does the same three things by hand. This is exercises/36/06-add-and-done.go:

// download takes a pointer to the WaitGroup, so that Done changes the one
// that main waits on, not a copy.
func download(name string, wg *sync.WaitGroup) {
    defer wg.Done()

    time.Sleep(500 * time.Millisecond)
    fmt.Println("Done", name)
}

func main() {
    var wg sync.WaitGroup
    files := []string{"a.txt", "b.txt", "c.txt"}
    for _, name := range files {
        wg.Add(1)
        go download(name, &wg)
    }
    wg.Wait()
    fmt.Println("All done")
}

One run printed:

Done c.txt
Done b.txt
Done a.txt
All done
  • wg.Add(1) adds one to the count. Call it before the go line, in main. If it were inside the goroutine, wg.Wait() could run before it and find a count of zero.
  • go download(name, &wg) starts the goroutine.
  • defer wg.Done() takes one off the count when download returns, on every path out of the function, as defer did for closing files in Chapter 31.

The parameter is a pointer, *sync.WaitGroup, as in Chapter 27. If download took a plain sync.WaitGroup, it would get a copy, and its Done would count down the copy. The one in main would never reach zero, and the program would stop with fatal error: all goroutines are asleep - deadlock!. Chapter 37 explains that message.

wg.Go does Add, go and Done for you, and you cannot forget any of them. Use it in your own code.

One slot each

Goroutines often compute something, and the program needs the answers. One safe way is to give each goroutine its own slot in a slice, made before they start. This is exercises/36/07-one-slot-each.go:

// slowSquare pretends that squaring a number takes a while.
func slowSquare(n int) int {
    time.Sleep(300 * time.Millisecond)
    return n * n
}

func main() {
    start := time.Now()

    numbers := []int{2, 3, 4, 5, 6}
    results := make([]int, len(numbers))

    var wg sync.WaitGroup
    for i, n := range numbers {
        wg.Go(func() {
            results[i] = slowSquare(n)
        })
    }
    wg.Wait()

    for i, n := range numbers {
        fmt.Printf("%d squared is %d\n", n, results[i])
    }
    fmt.Println("Took", time.Since(start).Round(100*time.Millisecond))
}

Output:

2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
6 squared is 36
Took 300ms

The goroutines finish in any order, but the answers come out in the original order, because each one wrote to results[i] with its own i. The printing happens after wg.Wait(), when every slot is filled.

This works because no two goroutines touch the same element. If several goroutines change the same variable, such as one shared total, answers get lost. Chapter 38 shows that problem and how to fix it. Chapter 37 shows another way to get answers back: goroutines send them over a channel.

Homework

Homework starters are in exercises/36/homework/. Each one runs as it is. Run them all from the go-work folder.

Problem 1 — Three greeters

Open exercises/36/homework/01-three-greeters.go. Using a sync.WaitGroup and wg.Go, start three goroutines that call sayHello with 1, 2 and 3. Wait for all three, then print All greeters finished. Run it a few times and compare the order.

Problem 2 — Wait for them

Open exercises/36/homework/02-wait-for-them.go. It starts three goroutines with go, but main does not wait, so the reports rarely appear. Make main wait for all three before it prints All reports in. Do not use time.Sleep in main.

Problem 3 — Breakfast

Open exercises/36/homework/03-breakfast.go. Three kitchen jobs run one after another, and breakfast takes about 1.2 seconds. Run them at the same time, so that breakfast takes about as long as the slowest job.

Challenge — Line counter

Open exercises/36/homework/04-line-counter.go. Count the lines of every file in the files slice at the same time, one goroutine per file, using the countLines function that is provided. Give each goroutine its own slot in a slice of result values, then print every file in the original order, with its line count or its error, and finish with the total.

Stuck or finished? Open the homework solutions page.