Multiple channels
- Go course
- Intermediate
- Lesson 14/80
- 4 min
Learn multiple cases inside select.
Multiple channels
select shows its power when waiting on many channels. case v := <-ch1: and case v := <-ch2: wait on two channels at once; whichever sends first runs.
This lets a goroutine gather data from many sources. For example a worker waits on both a jobs channel and a cancel channel; it reacts to whichever signals first.
Multi-channel pattern
A common pattern with multiple channels: one carries work, the other carries cancellation. select waits on both; if cancel arrives the goroutine exits, if work arrives it processes.
Combined with the context package this makes a strong cancellation mechanism. Workers are not killed; they check and exit themselves.
Practice Wait on multiple channels
Inside main, add a select { case ... case ... } block and print multi ready with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
ch1 := make(chan string)
ch2 := make(chan string)
go func() { ch1 <- "çoklu hazır" }()
select {
case m := <-ch1:
fmt.Println(m)
case m := <-ch2:
fmt.Println(m)
}
}Expected output
çoklu hazır
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If several cases are ready in select, what happens?
- The first case runs
- All run in order
- It errors
- A random one runs Correct answer
Explanation: a random one runs. Not the first; random pick is fair.
2 Multiple cases
select {
case v := <-ch1:
fmt.Println(v)
____:
fmt.Println("ch2")
}
select {
case v := <-ch1:
fmt.Println(v)
case v := <-ch2:
fmt.Println("ch2")
}
Explanation: case contains a channel operation.
3 Match multi-channel pattern
| Term | Meaning |
|---|---|
ch1 |
Work |
ch2 |
Cancel |
select |
Wait |
random |
Fair pick |