A waiter at Bimo's Meatball Stall stands at the kitchen pass. The tendon meatballs and the iced tea are being made in two different places, and he carries out whichever is ready first. While waiting, he keeps an eye on the clock. If it takes too long, he goes back to the customer and apologises.
Waiting on several things at once like this is written with select: a goroutine waits on several channel operations at once, then runs the case that is ready first. It looks like a switch, but each case is a send or a receive on a channel. The two places are channels, the clock is time.After.
select: whichever is ready first
In this program the tendon meatballs are ready in 3 seconds, the iced tea in 1 second, and time.After sets a limit of 2 seconds. Before you look at the output, guess: what does it print?
package main
import (
"fmt"
"time"
)
func cook(menu string, duration time.Duration) <-chan string {
ch := make(chan string, 1)
go func() {
time.Sleep(duration)
ch <- menu + " ready"
}()
return ch
}
func main() {
meatballs := cook("tendon meatballs", 3*time.Second)
icedTea := cook("iced tea", 1*time.Second)
select {
case msg := <-meatballs:
fmt.Println(msg)
case msg := <-icedTea:
fmt.Println(msg)
case <-time.After(2 * time.Second):
fmt.Println("timeout")
}
}
$ go run stall.go
iced tea ready
cookstarts a goroutine that sleeps forduration, then sends"<menu> ready". It returns a<-chan string, a channel that may only be received from.selectwaits until one of the cases is ready. The iced tea is ready at second 1, before the 2-second limit and the 3-second meatballs, soiced tea readyprints.- Only one case runs. The meatballs, ready later, are ignored by this
select. - When several cases are ready at once,
selectpicks one of them at random. The order of the cases in the code gives no priority.
Timeouts with time.After
time.After(d) returns a channel that receives one value after the duration d. Used as a case, it becomes a time limit. Change the iced tea to 4 seconds, and no dish is ready before second 2:
$ go run stall.go
timeout
The basic pattern:
select {
case msg := <-ch:
fmt.Println(msg)
case <-time.After(1 * time.Second):
fmt.Println("timeout")
}
If ch sends nothing within 1 second, the second case runs and timeout prints. Note the make(chan string, 1) in cook: a buffer of 1 lets its goroutine still send and finish even when nobody receives any more. Without the buffer, the losing meatballs goroutine would wait forever (a goroutine leak).
default: don't wait
Add default, and select never waits. If no case is ready at that moment, default runs at once:
select {
case msg := <-meatballs:
fmt.Println(msg)
case msg := <-icedTea:
fmt.Println(msg)
case <-time.After(2 * time.Second):
fmt.Println("timeout")
default:
fmt.Println("nothing is ready yet")
}
This program prints nothing is ready yet at second 0. default also helps to send without waiting: select { case queue <- m: ... default: fmt.Println("queue full, refused:", m) } refuses an order when the queue is full.
💡 Stopping a goroutine: a done channel and context
A goroutine that keeps working can be told to stop through a channel. close(done) makes every <-done ready at once:
func kitchen(done <-chan struct{}) {
for {
select {
case <-done:
fmt.Println("kitchen: stove turned off")
return
default:
fmt.Println("kitchen: boiling the broth")
time.Sleep(400 * time.Millisecond)
}
}
}
If main waits 1 second and then calls close(done), the output is kitchen: boiling the broth three times, then kitchen: stove turned off. The way the standard library does it is a context: ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second), then case <-ctx.Done():. Once the limit passes, ctx.Err() holds context deadline exceeded. Always call defer cancel().
Other patterns built from channels and select: a worker pool (a fixed set of goroutines taking jobs from one channel), fan-in (results from many goroutines gathered into one channel), and a pipeline (one stage's output is the next stage's input).
⚠️ A select that waits forever or spins without stopping
- No case can ever be ready. A
selectwithoutdefaultwaits forever; with no other goroutine, the program dies withfatal error: all goroutines are asleep - deadlock!andgoroutine 1 [select]. An emptyselect {}also waits forever. - Thinking the first case goes first. When two cases are ready together, the choice is random.
- A goroutine left behind by a timeout. Its result channel has no buffer and nobody receives any more: the goroutine is stuck forever. Use a buffer of 1.
defaultinside aforwith no pause. The loop spins without ever waiting and burns CPU. Add a pause, or dropdefaultsoselectwaits.breakinside aselect, inside afor.breakonly leaves theselect, and the loop goes round again. To leave the loop, usereturnaskitchendoes, or give thefora label and writebreak labelName.
TL;DR: select waits on several channel operations at once and runs the one case that is ready first; when several are ready together, one is picked at random. case <-time.After(1 * time.Second): fmt.Println("timeout") sets a time limit. default makes select not wait at all. Stop a goroutine with close(done) or a context (case <-ctx.Done()). A select with no case that can be ready waits forever, and give a result channel a buffer of 1 so a losing goroutine is not stuck.
⚡ Whichever is ready first
Write:
select {
case msg := <-meatballs:
fmt.Println(msg)
case msg := <-icedTea:
fmt.Println(msg)
case <-time.After(2 * time.Second):
fmt.Println("timeout")
}
Meaning: select waits on several channel operations at once, then runs the one case that is ready first. The iced tea is ready at second 1, so what prints is iced tea ready.
⚡ Case order is not priority
Guess first: two cases are ready at the same time. Does the one written on top win?
No. select picks one of them at random. The order of the cases in the code gives no priority.
Meaning: case <-time.After(1 * time.Second): sets a time limit. If nothing is ready by then, the timeout case runs.
⚡ default: don't wait
Write:
default:
fmt.Println("nothing is ready yet")
Meaning: With default, select never waits. If no case is ready at that very moment, default runs straight away.