Go · Chapter 17 of 26

Select and timeouts

By the end of this chapter you can wait on several channels at once with select, give up after a time limit with time.After, try a channel without waiting with default, switch a case off with a nil channel, do work on a beat with a time.Ticker, and stop a goroutine by closing a done channel. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Concurrency
  • 4 tasks
  • Go
  • In the all labs plan

The first 2 chapters of Go are free. This one comes with the all labs plan.

Why you need this

At 7:12 pm on Wednesday, when Tenzin was paged, the central system was taking more than 30 seconds to answer some status lookups. Every request that asked it waited the whole time, the requests behind it waited too, and chargers that heard nothing back marked themselves offline. A charger's own heartbeat comes every 30 seconds: an answer that arrives after a minute is no use to anyone. Nandini's rule for the new service is short: never wait longer than an answer is worth.

The Go you know from chapter 16 cannot keep that rule. A receive from a channel waits until something arrives, however long that takes, and a goroutine can wait on only one channel at a time. To say "the answer, or 100 ms, whichever comes first", one goroutine has to wait on two things at once. That is what select does.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    lookup.go: a status lookup that gives up after 100 ms

    Write StatusOrTimeout(c *bijli.Central, id string) (bijli.Status, error) in lookup.go. It asks c for charger id's status (c.ChargerStatus, with context.Background() as its first argument) and waits at most 100 ms for the answer.

    If the answer comes within 100 ms, return its status and error at once: with a central system that answers in 30 ms, StatusOrTimeout("C1042") must return C1042's status (station ST007) after exactly 30 ms. If no answer has come after 100 ms, return bijli.Status{} and ErrTimeout (declared in the starter): with a central system that takes 2 s, after exactly 100 ms. For the unknown charger C9999, return the central system's own error, which wraps bijli.ErrUnknownCharger.

    When StatusOrTimeout gives up, the goroutine that asked is still waiting for the central system. When the late answer comes, that goroutine must be able to hand it over and end: the Check runs your code with a fake clock, waits until the late answer has come, and fails if any goroutine is left stuck.

  2. Task 2

    replicas.go: the first of two replicas to answer wins

    Write FirstOf(a, b *bijli.Central, id string) (bijli.Status, error) in replicas.go. BijliGo runs the central system twice, a and b, with the same data. FirstOf asks both for charger id's status at the same time (with context.Background()) and returns whichever answer comes first, its status and its error, as soon as it comes.

    The Check makes one replica answer in 20 ms and the other in 1 s, both ways round, and asks for C1051: FirstOf must return C1051's status (station ST009) after exactly 20 ms, and must ask each replica exactly once.

    The slower replica answers too, later. Its goroutine must be able to hand over its answer and end, even though nobody is waiting for it any more: the Check fails if any goroutine is left stuck.

  3. Task 3

    beat.go: heartbeats on a ticker until told to stop

    Write Beat(c *bijli.Central, id string, every time.Duration, done <-chan struct{}) int in beat.go. Every interval every, record one heartbeat for charger id with c.RecordHeartbeat (context.Background(), and a bijli.Heartbeat whose Charger is id and whose At is the time of that tick), until done is closed. Then stop and return how many heartbeats were recorded.

    The first heartbeat comes one interval after Beat starts, not at once. With every = 10 ms and done closed after 105 ms, Beat records exactly 10 heartbeats and returns 10; with every = 25 ms and done closed after 110 ms, it records 4 and returns 4. It must return straight away when done is closed, before the next tick. If done is already closed when Beat starts, it records none and returns 0.

    The Check runs Beat with a fake clock, so these times are exact, and counts the heartbeats the central system recorded for C1042.

  4. Task 4 · interview question

    Interview: drain.go, the readings lost at stop

    Tenzin's Drain(energy <-chan int, stop <-chan struct{}) int adds up the Wh of readings from energy until stop is closed. energy is buffered and is never closed. At shutdown, readings already waiting in energy must still be counted, but Drain loses some of them, a different number each run.

    Fix Drain so that it keeps adding readings while stop is open, and once stop is closed, adds every reading still waiting in energy and then returns the total at once. The Check fills energy with 50 readings (6225 Wh in all), closes stop and calls Drain 20 times: every total must be 6225. It also starts Drain with energy empty and stop open (it must keep waiting), then sends 700 and 800 and closes stop: Drain must return 1500. Since energy is never closed, a loop that waits for it to close never ends.

    Joseph will ask: what does select do when two of its channels are ready at once?

What you will learn

  • select: waits on several channel operations and runs the first one that can go ahead.
  • time.After: a channel that receives once, after a time: a timeout as a select case.
  • default: a select case that runs when nothing else is ready, so the select never waits.
  • A nil channel in a select: a case that can never run, to switch it off.
  • time.Ticker and Stop: a channel that receives again and again, on a beat.
  • A done channel: closing it tells a goroutine to stop.

More in Concurrency

Build "Select and timeouts" yourself

BijliGo, a Bengaluru EV charging network, drops chargers at the evening peak. You rewrite its backend in Go. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Go are free. This one comes with the all labs plan.