Concept Flow - Select with multiple channels
Start
Wait for any channel
Chan1
Handle
Repeat or Exit
The program waits for messages from multiple channels and handles whichever is ready first, including a default case if none are ready.
package main import "fmt" func main() { c1 := make(chan string) c2 := make(chan string) select { case msg1 := <-c1: fmt.Println("Received", msg1) case msg2 := <-c2: fmt.Println("Received", msg2) default: fmt.Println("No message received") } }
| Step | Select Case | Channel Ready? | Action Taken | Output |
|---|---|---|---|---|
| 1 | case msg1 := <-c1 | No | Skipped | |
| 2 | case msg2 := <-c2 | No | Skipped | |
| 3 | default | N/A | Executed | No message received |
| 4 | End | N/A | Program ends |
| Variable | Start | After Select |
|---|---|---|
| msg1 | undefined | undefined |
| msg2 | undefined | undefined |
select {
case <-chan1:
// handle chan1
case <-chan2:
// handle chan2
default:
// handle no ready channel
}
- Waits for multiple channels
- Executes first ready case
- Default runs if none ready
- Useful for concurrent waitsWhat does the select statement do when used with multiple channels in Go?
select statement waits for one of its channel cases to be ready.Which of the following is the correct syntax to use select with two channels ch1 and ch2 for receiving values?
?
val := <-ch to assign the received value.val := <-ch1.What will be the output of the following Go program?
package main
import (
"fmt"
"time"
)
func main() {
ch1 := make(chan string)
ch2 := make(chan string)
go func() {
time.Sleep(100 * time.Millisecond)
ch1 <- "hello"
}()
go func() {
time.Sleep(50 * time.Millisecond)
ch2 <- "world"
}()
select {
case msg1 := <-ch1:
fmt.Println(msg1)
case msg2 := <-ch2:
fmt.Println(msg2)
}
}ch2 sleeps 50ms, and ch1 sleeps 100ms.ch2 sends first, the select will receive from ch2 and print "world".Identify the error in this Go code using select with multiple channels:
package main
import "fmt"
func main() {
ch1 := make(chan int)
ch2 := make(chan int)
select {
case val := <-ch1:
fmt.Println(val)
case val := <-ch2:
fmt.Println(val)
}
}ch1 and ch2 are unbuffered with no goroutines to send values.select blocks forever since no channels become ready, causing a deadlock.You want to write a Go function that waits on two channels chA and chB and returns the first value received from either. If neither channel is ready immediately, it should return "timeout" after 100 milliseconds. Which select structure correctly implements this?
time.After function returns a channel that sends a value after the specified duration, perfect for timeout.chA and chB return the first received value; the timeout case returns "timeout" after 100ms.Pass the test and this pattern moves unknown