go · level 3 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Closing a channel tells every listener at once: time to stop.
Sending a value wakes one receiver. Closing a channel wakes all of them, because a receive on a closed channel never waits. That makes close a : one call, and every goroutine listening hears it.
A channel used only as a signal carries no data, so give it the type chan struct{}. struct{} is the : a type with no fields, and its only value is written struct{}{}. Nothing travels down this channel except the news.
Workers listen for the signal with <-done, or inside a select with case <-done: return. Close done once, from the goroutine in charge, and every worker stops.
package main
import (
"fmt"
"strings"
"sync"
)
func main() {
done := make(chan struct{})
stopped := make([]string, 3)
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
<-done
stopped[i] = fmt.Sprint("worker ", i+1, " stopped")
}(i)
}
close(done)
wg.Wait()
fmt.Println(strings.Join(stopped, "\n"))
} A <-done on its own line waits for the signal and throws away the value it gets.
guess first
Peek at a closed done channel three times. What is the count?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
done := make(chan struct{})
close(done)
count := 0
for i := 0; i < 3; i++ {
select {
case <-done:
count++
default:
}
}
fmt.Println(count)
}
your turn
Your turn. Lock every door with one signal.
Fill in the empty struct type for the signal channel, then the call that wakes every waiting goroutine at once.
output
press run to see what happens
fix it
Only one worker goes home. Can you fix it?
output
press run to see what happens
- Two workers wait on
done, but only one value is sent. What happens to the other worker? - A send wakes exactly one receiver. Closing the channel wakes every receiver, now and later.
- Replace
done <- struct{}{}withclose(done).
nailed it
one close, and every worker hears it. :D
- Closing a channel wakes every receiver at once.
chan struct{}carries a signal and no data.- Close a done channel once, from the goroutine in charge.
new words in your collection
- broadcast
- empty struct
This lesson isn’t saved. A free account remembers every lesson you finish.