Skip to main content
InterviewHubPRO
Section Overview
Q18

Question 18 of 50

Part 2: Concurrency, Channels & The GMP Scheduler (16 - 32)

36%
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 default block 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")
}