Concept Flow - Why select is needed
Start
Multiple channels ready?
Select picks one
Execute case
End
The select statement waits on multiple channels and picks one that is ready to proceed, or blocks if none are ready.
select {
case msg1 := <-ch1:
fmt.Println("Received", msg1)
case msg2 := <-ch2:
fmt.Println("Received", msg2)
}| Step | Channels Ready | Select Action | Output |
|---|---|---|---|
| 1 | ch1 ready, ch2 not ready | Pick ch1 case | Print 'Received <msg1>' |
| 2 | ch2 ready, ch1 not ready | Pick ch2 case | Print 'Received <msg2>' |
| 3 | both ch1 and ch2 ready | Pick one case randomly | Print 'Received <msg1>' or 'Received <msg2>' |
| 4 | none ready | Block and wait | No output until a channel is ready |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|---|
| msg1 | nil | "<msg1>" | nil | "<msg1>" or nil | nil |
| msg2 | nil | nil | "<msg2>" | nil or "<msg2>" | nil |
select {
case <-ch1:
// handle ch1
case <-ch2:
// handle ch2
}
- Waits on multiple channels
- Picks one ready channel randomly
- Blocks if none ready
- Useful for concurrent communication