select, timeouts and default
select waits on several channel operations and takes the one that is ready. With one case it is a receive, with two it is a race the runtime resolves, and with a default it is a check that never blocks. A timeout is a select on a channel that fires later, which is how a Go program says "give up after this long" without a timer thread. The previous lesson filled channels; this one waits on several.
One of two channels
Two goroutines send to two different channels and the loop receives twice. Each iteration waits for whichever channel is ready first, and when both are ready the runtime picks a case at random, so the order of the two lines is not the order of the two goroutines. The loop still receives both values.
package main
import "fmt"
func main() {
first := make(chan string)
second := make(chan string)
go func() { first <- "one" }()
go func() { second <- "two" }()
for i := 0; i < 2; i++ {
select {
case v := <-first:
fmt.Println("first:", v)
case v := <-second:
fmt.Println("second:", v)
}
}
}
go build -o app main.go && ./app
second: two
first: one
A second run of the same binary printed the two lines in the other order. A select with several ready cases is deliberately fair rather than predictable: the runtime randomises the choice so that no channel is starved, and a program that needs an order must carry it in the data rather than in the case order.
A timeout
time.After returns a channel that receives one value after the duration. Used as a case, it turns a wait into a wait with a limit: the program receives either the answer or the timeout, and the other branch is abandoned. The goroutine that would have sent later is not stopped; a real program gives it a context so it can stop too, which is the subject of the next lessons.
package main
import (
"fmt"
"time"
)
func main() {
slow := make(chan string)
go func() {
time.Sleep(50 * time.Millisecond)
slow <- "late"
}()
select {
case v := <-slow:
fmt.Println("got:", v)
case <-time.After(10 * time.Millisecond):
fmt.Println("timeout after 10ms")
}
}
go build -o app main.go && ./app
timeout after 10ms
The sender sleeps fifty milliseconds and the receiver gives up after ten, so the timeout wins every time. A program that leaves the sender behind leaks a goroutine until the send completes or the program ends; here the whole program ends, which is the only reason the leak is invisible.
The default branch
A select with a default does not wait at all: it takes a ready case if there is one and runs the default otherwise. That makes it a non-blocking read or write, useful for a queue that drops work under load and for a cache lookup that must not stall a request. It is also the easiest way to write a busy loop by accident, because a default in a loop spins as fast as the CPU allows.
package main
import "fmt"
func main() {
messages := make(chan string, 1)
select {
case m := <-messages:
fmt.Println("received:", m)
default:
fmt.Println("nothing to receive")
}
messages <- "hello"
select {
case m := <-messages:
fmt.Println("received:", m)
default:
fmt.Println("nothing to receive")
}
}
go build -o app main.go && ./app
nothing to receive
received: hello
The first select found the channel empty and took the default; the second found the value and took the case. A nil channel in a select is never ready, which is the other half of this trick: switching a case off is as simple as setting its channel to nil.
A done channel
The loop below receives ticks until a done channel closes. The producer sends three values and closes done; the consumer returns on the close. This is the shutdown pattern the standard library uses everywhere, and it is the reason a closed channel is a broadcast: every receiver of a closed channel wakes up at once.
package main
import (
"fmt"
"time"
)
func main() {
done := make(chan struct{})
ticks := make(chan int)
go func() {
for i := 1; i <= 3; i++ {
ticks <- i
time.Sleep(5 * time.Millisecond)
}
close(done)
}()
for {
select {
case n := <-ticks:
fmt.Println("tick", n)
case <-done:
fmt.Println("done")
return
}
}
}
go build -o app main.go && ./app
tick 1
tick 2
tick 3
done
The three ticks are in order because they came through one channel and the consumer received each one before the producer could send the next. The close happened after the third send returned, so the done case could only fire afterwards. Replace the return with a break and the loop would run again, which is why the exit belongs in the select.
Exercises
- Run the two-channel program ten times and count the orders. Does the runtime ever starve one channel?
- Make the timeout longer than the sender's sleep and read the output. Which case wins, and what does the other goroutine do with its value?
- Put a select with a default in a loop and print a counter. How many iterations run in a second, and why is that a bug in a server?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does select do?
Answer
Waits on several channel operations and takes a ready one
It is the multi-way wait of Go.
-
What happens when two cases are ready at the same time?
Answer
The runtime picks one at random
Random choice prevents starvation.
-
What does time.After return?
Answer
A channel that fires after the duration
It is used as a case in a select.
-
What does a default branch do?
Answer
Runs when no case is ready, so the select does not block
In a loop it spins, which is usually a bug.
-
What does a nil channel do in a select?
Answer
Is never ready
Setting a channel to nil turns its case off.
-
Why is a closed channel a broadcast?
Answer
Every receiver on it wakes up
That is the shutdown pattern.
-
What happens to a goroutine whose send is abandoned by a timeout?
Answer
It waits until the send completes or the program ends
A context is the way to stop it too.
-
What does the loop in the done example return on?
Answer
The close of the done channel
The close wakes the done case.
-
How many cases can a select have?
Answer
Any number, plus an optional default
Each case is a channel operation.
-
In which order do the ticks of the done example arrive?
Answer
In the order they were sent
One channel keeps FIFO order.
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