37. Channels
Chapter 36 started goroutines and waited for them. To get answers
back, each goroutine wrote into its own slot of a slice, and
main read the slots after everything was done. That works
when you know in advance how many answers there will be, and you can
wait for all of them.
Often you want more: to use each answer as soon as it is ready, or to have one goroutine pass work on to the next while both keep running. A channel is made for this. It is a pipe between goroutines: one puts a value in at one end, and another takes it out at the other.
Make, send, receive
A channel is made with make, like a map, and it carries
values of one type:
answers := make(chan int)chan int is the type: a channel of int. Two
operations use the arrow <-, which points the way the
value moves:
- Send:
answers <- 49puts the value49into the channel. - Receive:
answer := <-answerstakes a value out of the channel.
Here is a goroutine that computes a value and sends it to
main, exercises/37/01-first-channel.go:
// Chapter 37 example: a goroutine sends a value, and main receives it.
// Run with: go run exercises/37/01-first-channel.go
package main
import (
"fmt"
"time"
)
// slowSquare pretends that squaring a number takes a while.
func slowSquare(n int) int {
time.Sleep(300 * time.Millisecond)
return n * n
}
func main() {
answers := make(chan int)
go func() {
answers <- slowSquare(7)
}()
fmt.Println("Waiting for the answer...")
answer := <-answers
fmt.Println("The answer is", answer)
}Output:
Waiting for the answer...
The answer is 49
go func() { ... }() starts a function literal (Chapter
36) in a new goroutine. The () at the end calls it, as with
any function. Without them, Go stops with
expression in go must be function call.
Notice that there is no sync.WaitGroup. The receive
<-answers waits until a value arrives,
so main cannot get past that line before the goroutine has
sent its answer. The channel carries the answer, and it also does the
waiting.
A send waits for a receiver
A channel made with make(chan int) is
unbuffered: it has no room to store anything. A value
is handed over directly, from one goroutine to another, so both must be
there at the same moment. A receive waits for a sender, and a send waits
for a receiver. This is exercises/37/02-send-waits.go:
func main() {
start := time.Now()
messages := make(chan string)
var wg sync.WaitGroup
wg.Go(func() {
fmt.Println("Sender: sending")
messages <- "hello"
fmt.Println("Sender: sent, after", time.Since(start).Round(100*time.Millisecond))
})
time.Sleep(time.Second)
fmt.Println("Main: receiving")
msg := <-messages
fmt.Println("Main: got", msg)
wg.Wait()
}One run printed:
Sender: sending
Main: receiving
Main: got hello
Sender: sent, after 1s
The sender was ready at once, but its send took a whole second,
because main was asleep and nobody was receiving. Only when
main reached <-messages could the value
pass. After that, both goroutines go on, so the last two lines can come
in either order.
Deadlock
What if a send waits for a receiver that never comes? Here
main sends on an unbuffered channel, and the only receive
is on the next line, in the same goroutine. This is
exercises/37/03-deadlock.go, and it crashes on purpose:
// Chapter 37 example: a deadlock, on purpose. This program crashes.
// Run with: go run exercises/37/03-deadlock.go
package main
import "fmt"
func main() {
messages := make(chan string)
messages <- "hello" // nobody is receiving, so this waits forever
fmt.Println(<-messages)
}Running it stops with:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
C:/go-work/exercises/37/03-deadlock.go:11 +0x36
exit status 2
main waits at the send for someone to receive. The
receive is in main too, so it can never be reached. Every
goroutine in the program is waiting for another one, and none can go on.
That is a deadlock. Go notices when all
goroutines are stuck, and stops the program, rather than letting it hang
forever.
Read the message as in Chapter 10. goroutine 1 is
main. [chan send] says it was stuck sending on
a channel, and the next lines give the file and line number: line 11,
the send. (The +0x36 at the end is a detail for Go itself,
and may differ on your computer.)
Go only reports a deadlock when every goroutine is stuck. If some other goroutine is still running, a stuck one just waits, with no message. In a web server, which always has goroutines waiting for visitors, a stuck request simply never finishes.
Buffered channels
A channel can have room to store some values. Give make
a second number, the size of the buffer:
messages := make(chan string, 3)Now a send only waits when the buffer is full, and a receive only
waits when it is empty. This is
exercises/37/04-buffered.go:
func main() {
messages := make(chan string, 3)
messages <- "one"
messages <- "two"
messages <- "three"
fmt.Println("Waiting in the channel:", len(messages))
fmt.Println(<-messages)
fmt.Println(<-messages)
fmt.Println(<-messages)
}Output:
Waiting in the channel: 3
one
two
three
The three sends go straight into the buffer, so main can
send and then receive on its own, which deadlocked a moment ago. Values
come out in the order they went in. len gives how many
values are waiting.
Open exercises/37/04-buffered.go. Add a fourth send,
messages <- "four", before the receives, and run it. The
buffer is full, nobody is receiving, and you get the deadlock error,
this time for line 14. Then make the buffer big enough.
A buffer does not make a program correct. It only lets a sender run ahead of the receiver by a few values. Start with unbuffered channels, and add a buffer when you have a reason, such as knowing exactly how many values will be sent.
Closing a channel, and
for range
A receiver often does not know how many values are coming. The sender
tells it with close, which means: no more values will
be sent on this channel. A for range loop over a
channel receives values until the channel is closed and empty, then
ends. This is exercises/37/05-close-and-range.go:
// countdown sends from..1, then closes the channel to say it is finished.
func countdown(from int, out chan int) {
for i := from; i >= 1; i-- {
out <- i
time.Sleep(200 * time.Millisecond)
}
close(out)
}
func main() {
numbers := make(chan int)
go countdown(5, numbers)
for n := range numbers {
fmt.Println(n)
}
fmt.Println("Liftoff!")
// After close, a receive gives the zero value at once, and ok is false.
n, ok := <-numbers
fmt.Println(n, ok)
}Output:
5
4
3
2
1
Liftoff!
0 false
The numbers appear one by one, a fifth of a second apart. Each one is printed as soon as it arrives, not at the end.
A receive from a closed channel does not wait. It gives the zero
value at once. To tell a real 0 from "closed", use the
two-value form, with the same v, ok shape as a map lookup:
ok is false when the channel is closed and
empty.
Three rules about close:
- The sender closes, never the receiver. Only the sender knows when there is no more to send.
- Sending on a closed channel crashes the program with
panic: send on closed channel. - You do not have to close every channel. Close one when a receiver
needs to know that the values have ended, as a
for rangeloop does. If the sender forgets to close it, the loop waits for more values forever, and the program stops with the deadlock error, this time with[chan receive].
Collecting results from several goroutines
Several goroutines can send on the same channel. Here four downloads
each send a result, and main receives exactly
four times. This is exercises/37/06-collect.go:
// result is what one download sends back.
type result struct {
name string
bytes int
}
// download pretends to fetch a file. Longer names take longer.
func download(name string) result {
time.Sleep(time.Duration(len(name)) * 100 * time.Millisecond)
return result{name: name, bytes: len(name) * 1000}
}
func main() {
start := time.Now()
files := []string{"notes.txt", "a.txt", "photo.png", "song.mp3"}
results := make(chan result)
for _, name := range files {
go func() {
results <- download(name)
}()
}
total := 0
for range len(files) {
r := <-results
fmt.Printf("%-10s %5d bytes\n", r.name, r.bytes)
total += r.bytes
}
fmt.Println("Total:", total, "bytes in", time.Since(start).Round(100*time.Millisecond))
}One run printed:
a.txt 5000 bytes
song.mp3 8000 bytes
photo.png 9000 bytes
notes.txt 9000 bytes
Total: 31000 bytes in 900ms
The results come in the order the downloads finish,
not the order they were started: the shortest first.
photo.png and notes.txt take the same time, so
those two can swap places from run to run.
Two things make this safe:
- Only
mainchangestotal. The goroutines never touch it. They send a value, andmaindoes the adding. Compare this with Chapter 36's warning about a shared total. mainreceives exactlylen(files)times, once per goroutine, so every goroutine can finish its send. Ifmainreceived fewer times, the remaining goroutines would wait forever at their send.
A result struct is a common way to send back more than
one value. When the work can fail, add an err error field,
as in the Chapter 36 challenge, and let the receiver decide what to do
with each error.
Wait, then close
Sometimes you do not know how many values will be sent. In
exercises/37/07-wait-then-close.go, twenty goroutines each
check one number, and only the primes are sent. To use
for range, someone has to close the channel once
every sender is done. A sync.WaitGroup
knows when that is:
func main() {
primes := make(chan int)
var wg sync.WaitGroup
for n := 1; n <= 20; n++ {
wg.Go(func() {
if isPrime(n) {
primes <- n
}
})
}
go func() {
wg.Wait()
close(primes)
}()
count := 0
for p := range primes {
fmt.Print(p, " ")
count++
}
fmt.Println()
fmt.Println(count, "primes up to 20")
}One run printed:
2 11 3 5 7 13 17 19
8 primes up to 20
The primes come in any order, and the count is always 8. Look at the
small goroutine in the middle. It waits for all the senders, then closes
the channel, and that ends the for range loop in
main.
Why a separate goroutine? If main called
wg.Wait() itself, before the loop, it would wait for
senders that are stuck, because nobody is receiving yet. That is a
deadlock. The waiting has to happen at the same time as the receiving.
Remember this pattern: senders with a WaitGroup, one goroutine
that waits and closes, and the receiver ranges over the
channel. Chapter 38 uses it for a worker pool.
Channel directions
A function that only sends on a channel can say so in its parameter type:
| Type | Meaning |
|---|---|
chan int |
send and receive |
chan<- int |
send only: the arrow points into chan |
<-chan int |
receive only: the arrow points out of chan |
You pass an ordinary chan int, and inside the function
it can only be used one way. If the function tries the other way, Go
stops before the program runs:
invalid operation: cannot send to receive-only channel <-chan int in (variable of type <-chan int)
This catches mistakes, and it tells the reader of the function at a glance which way the values flow. Use directions in function parameters whenever a function only sends or only receives.
A small pipeline
A pipeline is a chain of goroutines joined by
channels. Each stage receives values from the stage
before it, does one small job, and sends the result to the next stage.
This is exercises/37/08-pipeline.go:
// Chapter 37 example: a pipeline of three stages joined by channels.
// Run with: go run exercises/37/08-pipeline.go
package main
import "fmt"
// generate sends each number, then closes out.
func generate(numbers []int, out chan<- int) {
for _, n := range numbers {
out <- n
}
close(out)
}
// square receives numbers from in, and sends their squares to out.
func square(in <-chan int, out chan<- int) {
for n := range in {
out <- n * n
}
close(out)
}
func main() {
numbers := make(chan int)
squares := make(chan int)
go generate([]int{1, 2, 3, 4, 5}, numbers)
go square(numbers, squares)
sum := 0
for s := range squares {
fmt.Println(s)
sum += s
}
fmt.Println("Sum:", sum)
// Try this: add a stage, addOne, between square and main, that adds 1
// to every number. It needs a third channel.
}Output:
1
4
9
16
25
Sum: 55
The three stages run at the same time: while main prints
4, square can already be working on
3. But the order is fixed, because each stage handles one
value at a time, in the order it receives them.
Follow the closing down the chain. generate closes
numbers when it has sent everything. That ends the
for range in square, which then closes
squares. That ends the loop in main. Each
stage closes only the channel it sends on.
Open exercises/37/08-pipeline.go. Add a stage
addOne(in <-chan int, out chan<- int) between
square and main, that adds 1 to every number.
It needs a third channel. The sum should become 60.
What comes next
In every program in this chapter, each variable was changed by only
one goroutine. The others sent it values over a channel, and the owner
did the changing. That is often the simplest way. But sometimes several
goroutines really must change the same data, such as a map of visitors
in a web server. Chapter 38, Sharing data safely, shows
what goes wrong then, and how a sync.Mutex prevents it. It
also uses channels and a WaitGroup together to build a worker pool.
Homework
Homework starters are in exercises/37/homework/. Run
them all from the go-work folder. Each one runs as it is,
except Problem 3, which crashes on purpose until you fix it.
Problem 1 — Hand back a sum
Open exercises/37/homework/01-hand-back-a-sum.go. Start
a goroutine that computes sumUpTo(100) and sends the answer
on a channel. In main, print Working on it...,
then receive the answer and print
The sum of 1 to 100 is 5050.
Problem 2 — Shopping list
Open exercises/37/homework/02-shopping-list.go. Write
sendItems, which sends each item on a channel and closes it
at the end. In main, run it in a goroutine and use
for range to print each item with its number
(1. rice), then That is all.
Problem 3 — Fix the deadlock
Open exercises/37/homework/03-fix-the-deadlock.go and
run it. It stops with the deadlock error. Work out why, then fix it in
two ways: first by changing only the line that makes the channel, then
by keeping that line and sending the scores from a goroutine.
Challenge — Word lengths
Open exercises/37/homework/04-word-lengths.go. Build a
pipeline: words sends each word of the text,
lengths turns each word into a wordLength, and
main prints each one (send 4) and then the
longest word. Use chan<- and <-chan in
the parameters of words and lengths.
Stuck or finished? Open the homework solutions page.