Goroutines

A goroutine is a function that runs beside the one that started it. The syntax is go f(x), the cost is a few kilobytes of stack that grows as needed, and the rule that surprises everyone is that main does not wait for any of them: when main returns, the program ends and every goroutine ends with it. Part 5 finished with the build; Part 6 is about concurrency, and this is its first primitive.

A call that returns at once

The program starts a goroutine that prints a line and then prints its own line. The go statement returns immediately, so the scheduler decides whether the new goroutine runs before main reaches the end of the function. In five runs of this program the second line appeared once.

package main import "fmt" func main() { go fmt.Println("from the goroutine") fmt.Println("main returns") }

go build -o app main.go && ./app

main returns

The output is the rule, not a bug: a goroutine that has not finished gets no chance to finish. The program above is correct Go and a wrong program, and the toolchain says nothing about it. Every example that follows adds something that keeps main alive until the work is done.

Sleep is not a wait

The usual first fix is a sleep. It works often enough to be dangerous: the line appears because the goroutine had time, not because the program waited for it, and on a loaded machine or with a slower task the same code loses the line again. The sleep is a guess about time, and a program should not depend on a guess.

package main import ( "fmt" "time" ) func main() { go fmt.Println("from the goroutine") fmt.Println("main returns") time.Sleep(10 * time.Millisecond) }

go build -o app main.go && ./app

main returns
from the goroutine

The two lines appeared in the order the sleep allowed, and the program took ten milliseconds longer than it needed. A sleep in a test is worse: it makes the suite slow and still flaky, because the wait is a guess about the machine rather than a statement about the work.

Waiting with a WaitGroup

sync.WaitGroup is the primitive for "wait until these goroutines are done". Add sets the number of things to wait for before the goroutines start, each goroutine calls Done in a defer so a panic cannot skip it, and Wait blocks until the counter reaches zero. The counter is safe to use from several goroutines, which is its whole point.

package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() fmt.Println("from the goroutine") }() fmt.Println("main is not blocked") wg.Wait() fmt.Println("main continues after Wait") }

go build -o app main.go && ./app

main is not blocked
from the goroutine
main continues after Wait

The first line proves that go did not block; the last line proves that Wait waited. The order of the two worker lines is the scheduler's business, but the last line comes after both, every time.

One variable per iteration

A goroutine started inside a loop used to share the one loop variable, which is why old code copies it into a local before the go statement. Since Go 1.22 each iteration has its own variable, so the closure below sees the number of its own iteration. The order the goroutines print in is still not the order they were started.

package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup for i := 1; i <= 3; i++ { wg.Add(1) go func() { defer wg.Done() fmt.Println("goroutine", i) }() } wg.Wait() }

go build -o app main.go && ./app

goroutine 3
goroutine 2
goroutine 1

A second run of the same binary printed 3, 1, 2, and the set of numbers stayed 1, 2, 3. A program that needs the numbers in order must collect them and sort, or pass an index and place the result at that index; a program that only needs the lines does not care, and writing code that assumes an order is how a concurrency bug starts.

Exercises

  1. Run the first program ten times and count how often the goroutine line appears. What decides it on your machine?
  2. Replace wg.Add(1) and wg.Done() with a channel and a receive. Which version reads better for one goroutine, and which for ten?
  3. Start three goroutines and have each send its number to a buffered channel. Collect the three numbers into a slice and sort them. Why is the sort the only way to get a stable order?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the go statement do?

    Answer

    Runs the function in a new goroutine and returns at once

    The scheduler decides when the new goroutine runs.

  2. What happens when main returns while goroutines are running?

    Answer

    The program ends and they end with it

    Nothing waits for a goroutine unless the program does.

  3. Why is time.Sleep a bad way to wait for a goroutine?

    Answer

    It guesses a duration instead of waiting for the work

    A guess is flaky on a slower machine or a longer task.

  4. What is wg.Add(1) for?

    Answer

    It records one thing to wait for

    Add must run before the goroutine it counts.

  5. Why put wg.Done in a defer?

    Answer

    So it runs even when the goroutine panics

    A skipped Done makes Wait hang forever.

  6. What does wg.Wait() do?

    Answer

    Blocks until the counter reaches zero

    It is the join point of the group.

  7. Since Go 1.22, what does a closure in a loop capture?

    Answer

    The variable of its own iteration

    Each iteration declares a new variable.

  8. Does the number in the goroutine output follow the start order?

    Answer

    No, the scheduler decides the order

    The set is stable and the order is not.

  9. Which primitive waits for a group of goroutines?

    Answer

    sync.WaitGroup

    Add, Done and Wait are its three methods.

  10. How much stack does a new goroutine start with?

    Answer

    A small stack that grows as needed

    That is why a program can have many thousands of them.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev