39. select, timeouts and context
The goroutines in the last three chapters ran until their work was done. Real programs need to stop work early as well: a download that takes too long, a search the user no longer wants, a tool that should finish politely when you press Ctrl+C.
This chapter gives you three tools for that.
select waits on several channels at once.
Timeouts give up when something takes too long. And a
context carries one message to every goroutine that is
working on a job: stop now. With these, you have everything the
Duplicate Finder at the end of this part needs.
select: wait on
several channels
A receive <-ch waits for one channel.
select waits for several, and goes on with whichever is
ready first. This is exercises/39/01-select.go:
func main() {
tea := make(chan string)
toast := make(chan string)
go func() {
time.Sleep(300 * time.Millisecond)
tea <- "tea is ready"
}()
go func() {
time.Sleep(100 * time.Millisecond)
toast <- "toast is ready"
}()
for range 2 {
select {
case msg := <-tea:
fmt.Println("Tea channel:", msg)
case msg := <-toast:
fmt.Println("Toast channel:", msg)
}
}
}Output:
Toast channel: toast is ready
Tea channel: tea is ready
select looks like the switch from Chapter
16, but each case is a channel operation. It waits until
one of them can go ahead, runs that one case, and is done. The others
are not touched. Here the toast is ready after 100 milliseconds, so the
first select takes it, and the second select,
in the next round of the loop, takes the tea.
A plain receive on tea first would have waited 300
milliseconds for the tea while the toast sat ready. select
takes things in the order they actually happen.
If several cases are ready at the same moment, select
picks one of them at random. Do not count on the order of the cases.
Giving up: time.After
time.After(d) returns a channel that gets one value
after the duration d. Put it in a select next
to the real work, and you have a time limit. This is
exercises/39/02-timeout.go:
// slowAnswer works for the given time, then sends its answer. The channel has
// room for one value, so the send never blocks, even if nobody is waiting any
// more.
func slowAnswer(work time.Duration) <-chan int {
answer := make(chan int, 1)
go func() {
time.Sleep(work)
answer <- 42
}()
return answer
}
// ask waits for an answer, but not for longer than limit.
func ask(work time.Duration, limit time.Duration) {
select {
case n := <-slowAnswer(work):
fmt.Println("The answer is", n)
case <-time.After(limit):
fmt.Println("Gave up after", limit)
}
}
func main() {
ask(200*time.Millisecond, time.Second)
ask(3*time.Second, time.Second)
}Output:
The answer is 42
Gave up after 1s
The first answer takes 200 milliseconds, well inside the limit of one
second. The second would take three seconds, so after one second the
time.After channel is ready first, and ask
gives up. slowAnswer and time.After are both
called when the select starts, so the work and the clock
start together.
Look at the comment on slowAnswer. The channel is
buffered, with room for one value. When
ask gives up, nobody will ever receive the answer. With an
unbuffered channel, the goroutine would wait at its send forever. That
is a goroutine leak: a goroutine that is stuck, and
takes up memory, until the program ends. In a server that runs for
weeks, leaks add up. With a buffer of one, the send goes into the buffer
and the goroutine finishes, whether anyone is listening or not.
Open exercises/39/02-timeout.go and add a third call,
ask(time.Second, time.Second), where the work and the limit
are the same. Run it several times. Which line do you get? Both are
possible: when two cases are ready at nearly the same moment, either one
can win.
Not waiting: default
A select with a default case does not wait
at all. If no other case is ready right now, it runs
default at once. This is
exercises/39/03-default.go:
// tryReceive takes a message if one is waiting, and does not wait otherwise.
func tryReceive(messages chan string) {
select {
case msg := <-messages:
fmt.Println("Got:", msg)
default:
fmt.Println("Nothing yet.")
}
}
// trySend sends if there is room, and reports if there is not.
func trySend(messages chan string, msg string) {
select {
case messages <- msg:
fmt.Println("Sent:", msg)
default:
fmt.Println("Full, dropped:", msg)
}
}
func main() {
messages := make(chan string, 1)
tryReceive(messages)
trySend(messages, "hello")
trySend(messages, "again")
tryReceive(messages)
tryReceive(messages)
}Output:
Nothing yet.
Sent: hello
Full, dropped: again
Got: hello
Nothing yet.
A case can send as well as receive. The channel has room
for one message, so the first send fits, and the second finds it full
and is dropped. Everything in this program happens in main,
and nothing ever waits, so there is no deadlock.
Use default when waiting would be wrong, for example
when dropping a progress message is better than holding up the work.
Most of the time, you want select to wait, so leave
default out.
A steady beat:
time.NewTicker
time.After fires once. A ticker fires
again and again, at a steady interval, on its channel C.
This is exercises/39/04-ticker.go:
func main() {
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
stop := time.After(2200 * time.Millisecond)
start := time.Now()
for {
select {
case <-ticker.C:
fmt.Println("tick at", time.Since(start).Round(100*time.Millisecond))
case <-stop:
fmt.Println("Done.")
return
}
}
}Output:
tick at 500ms
tick at 1s
tick at 1.5s
tick at 2s
Done.
for with select inside is the shape you
will see most often: a loop that handles whatever happens next, again
and again, until one case ends it with return. Here the
ticker ticks every half second, and after 2.2 seconds the
stop channel ends the loop.
defer ticker.Stop() turns the ticker off when the
function returns. Stop every ticker you make, so that it does not keep
ticking for nobody.
The receive <-ticker.C throws the value away. A
ticker sends the current time, but here only the beat matters, as it did
with time.After.
Why a context
A timeout in one select is fine for one wait. But real
work is usually a chain: main calls a function, which
starts workers, which each do many steps. When the user presses Ctrl+C,
or the time is up, all of them should stop. Passing a
separate stop channel to every function by hand gets
messy.
The context package solves this. A
context, of type context.Context, is a
value that you pass down to every function that does part of the work.
It answers two questions:
ctx.Done()returns a channel that is closed when the work should stop. A closed channel is ready to receive at once, as Chapter 37 showed, so aselectwithcase <-ctx.Done():notices straight away. And because a closed channel is ready for every receiver, one context can stop any number of goroutines.ctx.Err()says why. It isnilwhile the work may go on. After that, it iscontext.DeadlineExceeded(the time ran out) orcontext.Canceled(someone said stop). Printed, they readcontext deadline exceededandcontext canceled.
You never close the Done channel yourself. You make a
context with a rule for when it is done, and the context
package closes the channel for you.
A time limit:
context.WithTimeout
This is exercises/39/05-with-timeout.go:
// countSlowly prints the numbers from 1 to n, one every 300 milliseconds. It
// stops early, and returns ctx.Err(), if ctx is done first.
func countSlowly(ctx context.Context, n int) error {
for i := 1; i <= n; i++ {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(300 * time.Millisecond):
fmt.Println(" ", i)
}
}
return nil
}
// run counts to n, with limit as the time limit.
func run(n int, limit time.Duration) {
fmt.Printf("Counting to %d, with %v:\n", n, limit)
ctx, cancel := context.WithTimeout(context.Background(), limit)
defer cancel()
err := countSlowly(ctx, n)
if err != nil {
fmt.Println("Stopped:", err)
return
}
fmt.Println("Finished.")
}
func main() {
run(3, 2*time.Second)
run(10, time.Second)
}Output:
Counting to 3, with 2s:
1
2
3
Finished.
Counting to 10, with 1s:
1
2
3
Stopped: context deadline exceeded
Counting to 3 takes 900 milliseconds, inside the two-second limit.
Counting to 10 would take three seconds, and after 3, at
900 milliseconds, the next number would come at 1.2 seconds. The context
is done at 1 second, so countSlowly returns
context.DeadlineExceeded.
Step by step:
context.Background()is an empty context, which is never done. Every context starts from one. It is the top of the chain.context.WithTimeout(parent, limit)makes a new context that is done whenlimithas passed. It returns the context and a cancel function.defer cancel()calls the cancel function whenrunreturns. That frees what the context holds, such as its timer, even when the work finished early. Always do this.go vetwarns if a cancel function is never called.countSlowly(ctx, n)gets the context as its first parameter, namedctx. This is a firm Go habit: any function that might take a while, or that calls one that might, takesctx context.Contextfirst.- Inside, each step is a
selectbetween the work andctx.Done(). When the context is done, the function returnsctx.Err(), an ordinaryerrorthat the caller handles like any other.
Because ctx.Err() returns these two error values, you
can test for them with errors.Is, as in Chapter 33:
errors.Is(err, context.DeadlineExceeded) is true when the
time ran out, and errors.Is(err, context.Canceled) when
someone cancelled.
Open exercises/39/05-with-timeout.go. Change the second
call to run(10, 4*time.Second) and check that it finishes.
Then find the smallest limit, to the nearest 100 milliseconds, with
which counting to 5 still finishes.
Stopping on demand:
context.WithCancel
Sometimes there is no clock. You just want to say "stop" when you
decide to. context.WithCancel makes a context that is done
when you call its cancel function. This is
exercises/39/06-cancel.go:
// worker does one step of work every 400 milliseconds, until ctx is cancelled.
func worker(ctx context.Context, id int) {
for step := 1; ; step++ {
select {
case <-ctx.Done():
fmt.Printf("worker %d: stopping (%v)\n", id, ctx.Err())
return
case <-time.After(400 * time.Millisecond):
fmt.Printf("worker %d: step %d\n", id, step)
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var wg sync.WaitGroup
for id := 1; id <= 3; id++ {
wg.Go(func() {
worker(ctx, id)
})
}
time.Sleep(time.Second)
fmt.Println("main: cancel")
cancel()
wg.Wait()
fmt.Println("main: every worker has stopped")
}One run printed:
worker 1: step 1
worker 3: step 1
worker 2: step 1
worker 2: step 2
worker 1: step 2
worker 3: step 2
main: cancel
worker 3: stopping (context canceled)
worker 1: stopping (context canceled)
worker 2: stopping (context canceled)
main: every worker has stopped
The workers come in a different order on each run, but every worker
does two steps, at 400 and 800 milliseconds, before main
cancels at one second. One call to cancel
stops all three, because they all watch the same ctx.Done()
channel, and closing it wakes every one of them.
for step := 1; ; step++ is a for loop with
no condition, so it goes on until a return. Calling
cancel a second time, as the defer does here,
is harmless.
A worker pool with a time limit
Chapter 38's worker pool ran until every job was done. Here is the
same pool with a context, so that it stops when the time is up. Both the
sender and the workers watch the context. This is
exercises/39/07-pool-with-context.go:
// doJob pretends to work on job n for 200 milliseconds. It gives up if ctx is
// done first.
func doJob(ctx context.Context, n int) (int, error) {
select {
case <-ctx.Done():
return 0, ctx.Err()
case <-time.After(200 * time.Millisecond):
return n * n, nil
}
}
// worker takes jobs until the channel is closed, or until ctx is done.
func worker(ctx context.Context, jobs <-chan int, results chan<- int) {
for n := range jobs {
square, err := doJob(ctx, n)
if err != nil {
return
}
results <- square
}
}
// sendJobs sends the numbers from 1 to count, and stops early if ctx is done.
// Either way, it closes jobs.
func sendJobs(ctx context.Context, count int, jobs chan<- int) {
defer close(jobs)
for n := 1; n <= count; n++ {
select {
case <-ctx.Done():
return
case jobs <- n:
}
}
}main makes a context with a limit of half a second,
starts three workers and the sender, closes results when
the workers are done, and counts the results:
done := 0
for range results {
done = done + 1
}
fmt.Printf("Finished %d of 20 jobs.\n", done)
if ctx.Err() != nil {
fmt.Println("Stopped early:", ctx.Err())
}Output:
Finished 6 of 20 jobs.
Stopped early: context deadline exceeded
Three workers finish three jobs at 200 milliseconds and three more at 400. The third round would end at 600, but the context is done at 500, so those three jobs give up halfway, and their workers return. Follow how everything stops:
- The sender is waiting to send job 10, because no
worker is free. Its
selecthas two cases, a send andctx.Done(), so it stops waiting, returns, and itsdefer close(jobs)closes the channel. A send in aselectis exactly as useful as a receive. - Each worker is inside
doJob, which returnsctx.Err(). The worker returns too. Even if it had been between jobs, the closedjobschannel would end its loop. - The closer sees the WaitGroup reach zero and closes
results, which ends the loop inmain.
Nobody is left waiting, and no goroutine leaks. Every place that
might wait for a long time, a send, a receive, or slow work, has a way
out through ctx.Done().
A worker can also check the context without a select:
if ctx.Err() != nil is a quick way to ask "should I still
start this job?" before beginning a piece of work that cannot be
interrupted, such as reading a file. The Duplicate Finder does that.
Open exercises/39/07-pool-with-context.go. Change the
limit to 2 seconds. How many jobs finish now? Then try 5 workers with a
limit of 500 milliseconds.
Ctrl+C:
signal.NotifyContext
When you press Ctrl+C in the terminal, the operating system sends the running program an interrupt signal. Normally, Go ends the program on the spot. Anything not saved is lost, and a file being written can be left half-written.
signal.NotifyContext, from the os/signal
package, turns Ctrl+C into a context that is done. Your program can then
stop the way it stops for a timeout: politely, after cleaning up. This
is exercises/39/08-ctrl-c.go:
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
fmt.Println("Working. Press Ctrl+C to stop.")
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
seconds := 0
for {
select {
case <-ticker.C:
seconds = seconds + 1
fmt.Println("Still working, second", seconds)
case <-ctx.Done():
stop() // a second Ctrl+C now ends the program at once
fmt.Println("Ctrl+C pressed. Saving and closing...")
time.Sleep(500 * time.Millisecond) // pretend to save
fmt.Printf("Stopped cleanly after %d seconds.\n", seconds)
return
}
}
}Run it, wait a few seconds, and press Ctrl+C:
Working. Press Ctrl+C to stop.
Still working, second 1
Still working, second 2
Still working, second 3
Ctrl+C pressed. Saving and closing...
Stopped cleanly after 3 seconds.
signal.NotifyContext(parent, os.Interrupt)returns a context that is done when the program gets an interrupt, and a function, here calledstop.os.Interruptis the signal that Ctrl+C sends, on Windows as well as on Linux and macOS.stop()puts things back the way they were: after it, Ctrl+C ends the program at once again.defer stop()does that at the end. Calling it as soon as the first Ctrl+C arrives means that an impatient user can press Ctrl+C a second time to quit without waiting for the clean-up.- The rest is the loop from the ticker example, with
ctx.Done()in place of the time limit.
Since the result is an ordinary context, everything from this chapter
works with it. Pass ctx to your workers, and Ctrl+C stops
the whole pool. ctx.Err() is context.Canceled
after Ctrl+C.
os.Exit, from Chapter 32, ends the program without
running deferred calls. If main exits with an error code
after the context is done, call stop() (or
cancel()) yourself first, as in:
if err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
stop() // os.Exit skips deferred calls
os.Exit(1)
}The program is ending anyway, so nothing breaks if you forget. But it keeps the rule simple: every context you make is cleaned up, on every path.
The rules, in one place
- A function that may take a while takes
ctx context.Contextas its first parameter, and passes it on to the functions it calls. - Make a context with
context.WithTimeout,context.WithCancelorsignal.NotifyContext, and call its cancel function withdeferstraight away. - Anywhere a goroutine might wait (a send, a receive, slow work), use
a
selectwithcase <-ctx.Done():as a way out. Before starting a job that cannot be interrupted, checkctx.Err(). - When the context is done, return
ctx.Err(), and let the caller decide what to tell the user.errors.Is(err, context.Canceled)tells a Ctrl+C from any other error. - A goroutine that sends a result nobody may wait for gets a channel with a buffer of one, so it can always finish.
Homework
Homework starters are in exercises/39/homework/. Run
them all from the go-work folder. Each one runs as it is,
but none of them can be stopped early yet.
Problem 1 — The fastest mirror
Open exercises/39/homework/01-fastest-mirror.go. The
same file can be downloaded from three mirrors, and
askMirror is finished. Write fastest, which
asks all three at once and returns the name of the first mirror to
answer, or "none" if no answer comes within the limit. With
one second, it prints mirror B. With 100 milliseconds,
none.
Problem 2 — A download with a time limit
Open exercises/39/homework/02-download.go. The download
takes 2.4 seconds. Add a -timeout flag with
flag.Duration, as in Chapter 35, defaulting to one second.
Make a context with that timeout, pass it to download as
its first parameter, and stop when it is done. On success, print
Download complete. When stopped, print
Download stopped: and the error to stderr, and exit with
code 1.
Problem 3 — A countdown you can stop
Open exercises/39/homework/03-countdown.go. Count down
from 5 to 1, one number per second, using a time.NewTicker,
then print Liftoff!. If the user presses Ctrl+C during the
countdown, print Countdown stopped at N., where
N is the last number shown.
Challenge — A pool with a progress line
Open exercises/39/homework/04-progress.go. Twelve jobs,
four workers, and job n takes n times 100
milliseconds. While the workers run, main prints a progress
line every half second, such as progress: 5 of 12 done,
then All 12 jobs done. at the end. Ctrl+C stops the
workers, even in the middle of a job, and main prints
Stopped by Ctrl+C after N of 12 jobs.
Stuck or finished? Open the homework solutions page.