Go · Chapter 16 of 26

Channels

By the end of this chapter you can make channels and send and receive on them, tell an unbuffered channel's handshake from a buffered channel's queue, close a channel and range over it, give a function a send-only or receive-only channel, build a pipeline of stages, merge several senders into one channel, and say who closes a channel and why. 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

The ingest service is a line of steps. Meter readings arrive from chargers; one step works out each session's energy; another records it; another updates the status cache. In chapter 15 each goroutine wrote its answer into its own element of a slice, and the caller looked only after everything had finished. That is fine for "ask 50 chargers and wait". It does not work when readings keep arriving all evening and every step should start on a reading as soon as the step before it has finished with it.

You also saw what happens when two goroutines share a variable: Tenzin's count lost heartbeats, and the race detector shouted. Go's answer is a saying from its authors: do not communicate by sharing memory; share memory by communicating. One goroutine hands a value to another through a channel, and after the hand-over only the receiver uses it.

What you build: 4 tasks

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

  1. Task 1

    pipeline.go: a pipeline stage, from readings to session totals

    Write Totals(in <-chan bijli.Reading) <-chan SessionTotal, one stage of a pipeline. It returns a channel at once, before reading anything (the Check sends the readings only after Totals has returned). A goroutine of its own reads readings from in until in is closed, then sends one SessionTotal for each session (Session, its Charger, and EnergyWh, its largest MeterWh) in the order each session first appeared, and closes the channel it returned.

    For ST001's 1263 readings it sends 24 totals adding up to 345154 Wh, the first S900710 on C1002 with 4720 Wh and the last S900475. For a closed channel with no readings it sends nothing and closes. The Check runs under the race detector.

  2. Task 2

    queue.go: a buffered queue of heartbeats

    Write Fill(hbs []bijli.Heartbeat) <-chan bijli.Heartbeat: it returns a channel with room for every heartbeat, already holding all of them in order (C1001's first for BijliGo's chargers), and closed. It starts no goroutine: for 1180 heartbeats, the moment Fill returns, the channel's length and capacity are both 1180.

    Write Drain(ctx context.Context, c *bijli.Central, q <-chan bijli.Heartbeat) int: it takes heartbeats out of q one at a time, records each with c.RecordHeartbeat (passing ctx on), stops when q is closed and empty, and returns how many were recorded without an error. After the Check takes C1001's heartbeat out, Drain of the rest returns 1179 with one call at a time; for C1005, C9999 (unknown) and C1006 it returns 2.

  3. Task 3

    merge.go: two stations' readings on one channel

    Write Merge(a, b <-chan bijli.Reading) <-chan bijli.Reading. It returns one channel at once, passes on every reading from a and every reading from b as they arrive, and closes its channel when both a and b are closed and every reading has been passed on.

    The Check sends 30 readings on a and 20 on b and expects all 50 to come out, then a closed channel. It also keeps a open, and quiet, until three of b's readings have come out: reading a to the end before starting on b waits forever. The Check runs under the race detector.

  4. Task 4 · interview question

    Interview: first.go, the channel closed too early

    FirstAvailable(ctx context.Context, c *bijli.Central, ids []string) string asks for every charger at once and returns the first one to answer that is available, or "" if none is. Tenzin's version closes the channel as soon as it has its answer, and the goroutines still sending crash the service with panic: send on closed channel (under the race detector, as in the Check, it is reported as a data race on the send, line 37).

    Fix it so that for ST003's seven chargers (C1015 to C1021) it returns an available one (any but C1019, which is faulted), with one call each; returns "" for C1015 and C1016 not answering and C1019; never panics; and leaves no goroutine waiting forever once it has returned (the Check counts the goroutines afterwards).

    Joseph will ask: who should close a channel, and why never the receiver?

What you will learn

  • make(chan T), send and receive: ch <- v sends, v := <-ch receives.
  • Unbuffered channels: a handshake; the sender waits for a receiver.
  • Buffered channels: a queue with room for n values; len and cap.
  • close, range and the ok form: "no more values", and how a receiver knows.
  • Direction types: chan<- T only sends, <-chan T only receives.
  • Pipelines: stages joined by channels, each its own goroutine.
  • Deadlock: fatal error: all goroutines are asleep - deadlock!, and who closes.

More in Concurrency

Build "Channels" 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.