The cashier at Bimo's Meatball Stall doesn't stand there waiting for the meatballs to be ready. Each order is handed to a cook in the kitchen, and the cashier moves straight on to the next customer. Three cooks can cook at once while the cashier keeps taking orders.
In Go, each of those cooks is a goroutine: a function that runs alongside other functions. To start one, just write go in front of a function call. The cashier is main. But there is one hard rule: as soon as the cashier goes home, the stall closes, and every cook goes home too, whether the food is done or not.
Starting a goroutine with go
package main
import "fmt"
func cook(table int, menu string) {
fmt.Println("kitchen: table", table, menu, "ready")
}
func main() {
go cook(1, "tendon meatballs")
go cook(2, "chicken noodles")
go cook(3, "iced tea")
fmt.Println("till: 3 orders in")
}
go cook(1, "tendon meatballs")startscookin a new goroutine, andmaingoes straight on to the next line without waiting.- The same function can still be called normally,
cook(1, "tendon meatballs"), and thenmainwaits for it to finish. mainitself is a goroutine too, the first one. A Go program stops as soon asmainends.
Before you look at the output below, guess: main starts three cook goroutines, prints till: 3 orders in, then ends. How many lines come out in the terminal?
main does not wait
$ go run stall.go
till: 3 orders in
Just one line. main prints the till line and ends, and once main ends the program stops along with all its goroutines, before a single one gets to print. In 8 tries on the Go Playground it was always this one line, but on another machine a kitchen line sometimes slips out. Nothing is promised.
time.Sleep only guesses
Adding time.Sleep(100 * time.Millisecond) before main ends makes all three kitchen lines appear, because cooking is quick. But if every dish takes 200 ms:
$ go run stall.go
till: 3 orders in
till: all orders ready
The till says every order is ready while none is done. Sleep only guesses how long to wait, and the guess can be wrong at any time.
sync.WaitGroup: wait until everything is done
A sync.WaitGroup is a counter of work not yet finished:
package main
import (
"fmt"
"sync"
)
func cook(table int, menu string, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Println("kitchen: table", table, menu, "ready")
}
func main() {
var wg sync.WaitGroup
wg.Add(3)
go cook(1, "tendon meatballs", &wg)
go cook(2, "chicken noodles", &wg)
go cook(3, "iced tea", &wg)
fmt.Println("till: 3 orders in")
wg.Wait()
fmt.Println("till: all orders ready")
}
$ go run stall.go
till: 3 orders in
kitchen: table 3 iced tea ready
kitchen: table 1 tendon meatballs ready
kitchen: table 2 chicken noodles ready
till: all orders ready
wg.Add(3)raises the count to 3, before the goroutines start.defer wg.Done()takes one off whencookends, whatever happens inside it.wg.Wait()blocksmainuntil the count is 0. Only then doestill: all orders readyprint, always last.- The WaitGroup is passed as a pointer,
&wg. Passed as a value, each goroutine holds a copy,Done()never lowersmain's count, and the program ends withfatal error: all goroutines are asleep - deadlock!.go vetfinds this mistake before the program runs:cook passes lock by value: sync.WaitGroup contains sync.noCopy.
The order is not fixed
The three kitchen lines above came out in the order 3, 1, 2. Run it again and the order can change. In 20 tries on the Go Playground (8 CPUs), 3, 1, 2 came up most often, but 1, 2, 3, then 2, 3, 1, 1, 3, 2, 3, 2, 1 and 2, 1, 3 came out as well. Goroutines are scheduled by the Go runtime, and the order they run in is not promised to match the order they were started. When order matters, synchronise explicitly.
Goroutines run concurrently: many jobs take turns, interleaved. On a processor with many cores they can also truly run at the same time (in parallel).
Why goroutines are cheap
A goroutine starts with a stack (the memory for its function calls) of about 2 KB, which grows by itself when needed. An operating system thread is usually given a stack measured in MB. Goroutines are also scheduled by the Go runtime, not by the operating system: the runtime spreads many goroutines over a few threads (called M:N scheduling). That is why one Go program can run thousands, even hundreds of thousands, of goroutines at once.
Since Go 1.22, loop variables are made fresh on every round, so for i, menu := range orders { go func() { ... menu ... }() } is safe: each goroutine holds its own menu. Since Go 1.25 there is also wg.Go(func() { ... }), which does the Add(1) and the Done() for you.
⚠️ Kitchen lines that vanish and a WaitGroup that gets stuck
- main ends first. Goroutines that have not finished stop with it, without any message. Wait with a WaitGroup (or a channel, in the next lesson).
- Sleep as the waiter. Sometimes it is enough, sometimes not. Don't rely on it.
wg.Addinside the goroutine.wg.Wait()can run before thatAddgets called. CallAddbeforego.- Forgetting
wg.Done(), or passingwgwithout&. The count never reaches 0, and the program dies withfatal error: all goroutines are asleep - deadlock!.
TL;DR: go f() runs f in a new goroutine, and the caller goes straight on. The program stops as soon as main ends, along with every goroutine not yet done, so without waiting you may only see till: 3 orders in. time.Sleep only guesses. Use a sync.WaitGroup: wg.Add(n) before go, defer wg.Done() inside the goroutine, wg.Wait() in main, and pass &wg. The order of goroutines is not fixed. Goroutines are cheap: a starting stack of about 2 KB, scheduled by the Go runtime, not the operating system.
⚡ go in front of a call
Write:
go cook(1, "tendon meatballs")
Meaning: cook runs in a new goroutine, and main goes straight on without waiting. A goroutine is cheap: its starting stack is about 2 KB, and it is scheduled by the Go runtime, not the operating system.
⚡ main doesn't wait
Guess first: main starts three cook goroutines, prints till: 3 orders in, then ends. How many lines come out?
Usually just one. As soon as main ends, the program stops along with every goroutine not yet done. time.Sleep only guesses how long to wait.
Meaning: Goroutines that haven't finished stop quietly along with main.
⚡ Wait with a WaitGroup
Write:
var wg sync.WaitGroup
wg.Add(3)
go cook(1, "tendon meatballs", &wg)
go cook(2, "chicken noodles", &wg)
go cook(3, "iced tea", &wg)
wg.Wait()
Meaning: wg.Add(3) before go, defer wg.Done() inside cook, and wg.Wait() holds main until the count is 0. Pass &wg, not a copy. The order of the kitchen lines is still not guaranteed.