Go Channels
"Do not communicate by sharing memory; instead, share memory by communicating." — a Go proverb
A channel is a typed pipe that goroutines use to send values to each other. One goroutine sends, another receives, and the channel takes care of synchronisation. Channels are Go's main tool for coordinating concurrent work safely.
Creating, sending and receiving
| Syntax | Meaning |
|---|---|
ch := make(chan int) |
create an unbuffered channel of int |
ch <- v |
send v into the channel |
v := <-ch |
receive a value from the channel |
v, ok := <-ch |
receive; ok is false if the channel is closed and empty |
close(ch) |
signal that no more values will be sent |
for v := range ch |
receive until the channel is closed |
package main
import "fmt"
func main() {
messages := make(chan string)
go func() {
messages <- "ping" // blocks until main is ready to receive
}()
msg := <-messages // blocks until a value arrives
fmt.Println("received:", msg)
}received: ping
Unbuffered channels synchronise
An unbuffered channel has no storage. A send blocks until another goroutine receives, and a receive blocks until another goroutine sends. Both sides meet at the same moment — a handshake. That makes the order of events predictable:
package main
import "fmt"
func main() {
ch := make(chan int)
done := make(chan bool)
go func() {
for v := range ch { // receives until ch is closed
fmt.Println("worker got", v)
}
fmt.Println("worker: channel closed")
done <- true
}()
for i := 1; i <= 3; i++ {
ch <- i
}
close(ch)
<-done // wait for the worker to finish printing
fmt.Println("main: finished")
}worker got 1
worker got 2
worker got 3
worker: channel closed
main: finished
Closing channels
close(ch) tells receivers that no more values are coming. After closing:
- receiving still returns any remaining values, then the zero value with
ok == false; - a
for rangeloop over the channel ends; - sending on a closed channel panics.
Only the sender should close a channel, and only when receivers need to know that the stream ended.
package main
import "fmt"
func main() {
ch := make(chan string, 2)
ch <- "a"
ch <- "b"
close(ch)
for i := 0; i < 3; i++ {
v, ok := <-ch
fmt.Printf("value=%q ok=%v\n", v, ok)
}
}value="a" ok=true
value="b" ok=true
value="" ok=false
Pipelines
Channels connect stages of work into a pipeline. Each stage is a goroutine that reads from one channel and writes to the next. Because each stage processes values in the order it receives them, the output order is preserved.
package main
import "fmt"
func generate(nums ...int) <-chan int {
out := make(chan int)
go func() {
for _, n := range nums {
out <- n
}
close(out)
}()
return out
}
func square(in <-chan int) <-chan int {
out := make(chan int)
go func() {
for n := range in {
out <- n * n
}
close(out)
}()
return out
}
func main() {
for result := range square(square(generate(1, 2, 3, 4))) {
fmt.Println(result)
}
}1
16
81
256
Directional channel types
A function parameter can restrict a channel to one direction. The compiler then rejects the wrong operation, which documents intent and prevents bugs.
| Type | Allowed |
|---|---|
chan T |
send and receive |
chan<- T |
send only |
<-chan T |
receive only |
In the pipeline above, generate returns a <-chan int, so callers can only read from it.
Deadlocks
If every goroutine is blocked waiting on a channel, nothing can ever proceed. The Go runtime detects this and stops the program:
package main
import "fmt"
func main() {
ch := make(chan int)
ch <- 42 // no one will ever receive: blocks forever
fmt.Println(<-ch)
}fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
./example.go:7 +0x36
The fix is to send from a different goroutine, or to give the channel a buffer (next chapter).
Tip: The zero value of a channel is
nil. Sending to or receiving from a nil channel blocks forever — always create channels withmake.
Test yourself
What happens when you send on an unbuffered channel and no goroutine is receiving?
- The value is dropped
- The sender blocks until a receiver is ready
- It panics immediately
- The value is stored for later
Which operation panics?
- Receiving from a closed channel
- Sending on a closed channel
- Ranging over a closed channel
- Closing a channel that still has values
What type is a receive-only channel of strings?
chan<- string<-chan stringchan string<-recv chan string