Golang & Concurrency (50 Qs)•Part 2: Concurrency, Channels & The GMP Scheduler (16 - 32)
How does the `select` Statement work, and what happens when multiple channels are ready?
senior LevelCode ExampleGolang
In Simple Words:
The select statement blocks until one of its cases is ready to communicate:
- If multiple cases are ready simultaneously, Go picks one pseudo-randomly via a uniform distribution (preventing starvation).
- If no case is ready and a
defaultblock exists, the default executes immediately (non-blocking channel poll). - If no case is ready and no default exists, the goroutine is suspended.
go
select {
case msg := <-ch1:
fmt.Println("Received from ch1:", msg)
case ch2 <- "ping":
fmt.Println("Sent ping to ch2")
case <-time.After(1 * time.Second):
fmt.Println("Timeout exceeded")
default:
fmt.Println("Non-blocking poll: no channel ready")
}