Course › Week 4 · Concurrency and plugging into Laravel › Day 2 · lesson 23 of 42 · 15 min reading + 60–75 min practice
Channels and select
Send values between goroutines, close a channel to say “done”, and wait on several with select.
A channel is a typed pipe between goroutines: one goroutine sends a value in, another receives it. Sending and receiving also synchronise the two, so a channel is both a way to pass data and a way to wait.
Go’s advice is “do not communicate by sharing memory; share memory by communicating”. Today shows what that means: channels, closing them, a buffer, the error you get when everyone waits, and select.
Channels
1. Send and receive
make(chan string) creates a channel of strings. ch <- value sends, value := <-ch receives. Both wait until the other side is ready.
package main
import (
"fmt"
"time"
)
func main() {
results := make(chan string)
go func() {
time.Sleep(50 * time.Millisecond) // stands in for a slow API call
results <- "rates for nyhavn: 12950"
}()
fmt.Println("waiting for the rates")
fmt.Println(<-results)
}
waiting for the rates
rates for nyhavn: 12950go func() { … }() starts a goroutine running a function literal; the () at the end calls it. The receive in main waits until the goroutine sends, so no WaitGroup is needed: the channel itself is the waiting.
2. close and range
The sender can close a channel to say “no more values”. for value := range ch receives until the channel is closed and empty.
package main
import "fmt"
// pendingIDs sends the IDs of the bookings to process, then closes the channel.
func pendingIDs(ids chan int) {
for _, id := range []int{1042, 1043, 1044} {
ids <- id
}
close(ids)
}
func main() {
ids := make(chan int)
go pendingIDs(ids)
for id := range ids {
fmt.Println("processing", id)
}
fmt.Println("no more bookings")
}
processing 1042
processing 1043
processing 1044
no more bookingsOnly the sender closes, and only once: sending on a closed channel panics. Receiving from a closed channel never waits; it returns the zero value at once, and v, ok := <-ch gives ok == false to tell you.
This is the shape of a queue worker: one goroutine produces jobs, another consumes them until there are no more.
3. A buffered channel
make(chan int, 3) has room for 3 values. A send waits only when the buffer is full; a receive waits only when it is empty.
package main
import "fmt"
func main() {
ids := make(chan int, 3)
ids <- 1042
ids <- 1043
fmt.Println("queued:", len(ids), "of", cap(ids))
fmt.Println(<-ids, <-ids)
}
queued: 2 of 3
1042 1043A buffer smooths out bursts: a producer can run a little ahead of a slower consumer. It is not a queue to store work in: when the program stops, whatever is in the buffer is lost. Laravel’s queue lives in Redis or the database for that reason.
4. A deadlock
Sending on an unbuffered channel waits for a receiver. If there is none, and no other goroutine could ever become one, the program can never continue:
package main
import "fmt"
func main() {
results := make(chan string)
results <- "done"
fmt.Println(<-results)
}
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/tmp/go-playbook/hello/main.go:8 +0x36
exit status 2Go detects that every goroutine is waiting and stops with all goroutines are asleep - deadlock!, exit code 2. It only notices when all of them wait; a deadlock between two goroutines while a third still runs just hangs, so a server can freeze without this message. The fix here is to send from another goroutine, or to give the channel a buffer of 1.
Results from many goroutines
5. One channel, many senders
Each goroutine sends its result into the same channel; main receives exactly as many results as it started goroutines.
package main
import (
"fmt"
"time"
)
type Rate struct {
Property string
Cents int
}
// fetchRate stands in for a call to a channel manager's API.
func fetchRate(property string, delay time.Duration) Rate {
time.Sleep(delay)
return Rate{Property: property, Cents: 10000 + int(delay/time.Millisecond)}
}
func main() {
delays := map[string]time.Duration{"nyhavn": 90 * time.Millisecond, "vesterbro": 10 * time.Millisecond, "amager": 50 * time.Millisecond}
rates := make(chan Rate)
for property, delay := range delays {
go func() {
rates <- fetchRate(property, delay)
}()
}
for range len(delays) {
r := <-rates
fmt.Println(r.Property, r.Cents)
}
}
vesterbro 10010
amager 10050
nyhavn 10090The results arrive in the order the calls finish, fastest first, not in the order they were started. Use this when you want each result as soon as it is ready; use one slot per goroutine (the goroutines lesson) when the order must match the input.
for range len(delays) receives exactly three times. Receive one fewer and a goroutine waits forever on its send: a goroutine leak, memory that is never freed in a long-running program.
6. select, and a timeout
select waits on several channel operations at once and runs the first one that is ready. With time.After(d), a channel that receives a value after d, it becomes a timeout.
package main
import (
"fmt"
"time"
)
func fetchRate(delay time.Duration) chan int {
result := make(chan int, 1)
go func() {
time.Sleep(delay)
result <- 12950
}()
return result
}
func main() {
for _, delay := range []time.Duration{20 * time.Millisecond, 300 * time.Millisecond} {
select {
case cents := <-fetchRate(delay):
fmt.Println("rate:", cents)
case <-time.After(100 * time.Millisecond):
fmt.Println("no answer within 100ms: using the cached rate")
}
}
}
rate: 12950
no answer within 100ms: using the cached rateThe second call took 300 ms, and select gave up after 100. The result channel has a buffer of 1, so the slow goroutine can still send its late answer and finish, instead of waiting forever for a receiver that left: no leak.
A timeout per call works, but every function then needs its own. Go’s standard way to give a whole chain of calls one deadline is context, in the next lesson.
7. Send-only and receive-only
A parameter of type chan<- int can only send, and <-chan int can only receive. The compiler enforces it, so the signature says who does what.
package main
import "fmt"
func produce(ids chan<- int) {
ids <- 1042
close(ids)
fmt.Println(<-ids)
}
func main() {
ids := make(chan int, 1)
produce(ids)
}
# hello
./main.go:8:16: invalid operation: cannot receive from send-only channel chan<- int ids (variable of type chan<- int)A plain chan int converts to either direction automatically when passed. Use the directions in every function that takes a channel: pendingIDs(ids chan<- int) in section 2 would have been the better signature.
Coming from PHP
<?php
// The nearest PHP shape: a queue between a producer and a consumer.
foreach ($pendingIds as $id) {
ProcessBooking::dispatch($id); // producer: push onto Redis
}
// php artisan queue:work // consumer: pop until stopped
A Laravel queue is a channel between processes, stored outside them so it survives restarts. A Go channel is a queue between goroutines of one process, in memory, with no persistence and no retries. They solve different problems: a Go worker often reads jobs from a durable queue (Redis, a database table) and then uses channels inside itself to spread the work.
PHP has nothing like select in everyday code; waiting on two things at once needs ReactPHP, Amp or Swoole. In Go it is a statement.
PracticeA Tour of Go: channels to select
In A Tour of Go, do the concurrency pages from Channels to Default Selection. The two binary-tree exercises after them are optional.
Exercise: first answer wins
Two price providers answer the same question; you want whichever answers first, and to give up after 200 ms. Write fastestRate(providers []func() int) (int, error) that starts each provider in a goroutine, returns the first result, and returns an error if none answers within 200 ms. Make sure the slower goroutines can always finish (hint: the buffer size).
Remember
- Only the sender closes a channel, after its last send; receivers
rangeuntil it is closed. - Receive as many results as you started goroutines, or give the channel a buffer, so no goroutine waits forever.
- Write
chan<-and<-chanin signatures.
Tomorrow: context for deadlines and cancelling, and calling HTTP APIs with timeouts and status checks.