Junior — Middle
How to organize simultaneous data reading from multiple channels?
sobes.tech AI
Answer from AI
To read from multiple channels simultaneously in Go, the select statement is usually used. It allows waiting on multiple channels and reacting to the first one that becomes available.
Example:
ch1 := make(chan int)
ch2 := make(chan int)
go func() { ch1 <- 1 }()
go func() { ch2 <- 2 }()
select {
case msg1 := <-ch1:
fmt.Println("Received from ch1:", msg1)
case msg2 := <-ch2:
fmt.Println("Received from ch2:", msg2)
}
Thus, select allows efficient processing of data from multiple sources without blocking.