Select
package main
import (
"fmt"
"time"
)
func main() {
// Creating two unbuffered channels, 'c1' and 'c2'
c1 := make(chan string)
c2 := make(chan string)
// Launching two goroutines to send messages to 'c1' and 'c2' after a specific time delay
go func() {
time.Sleep(1 * time.Second)
c1 <- "one"
}()
go func() {
time.Sleep(2 * time.Second)
c2 <- "two"
}()
// Looping twice to handle messages from 'c1' and 'c2'
for i := 0; i < 2; i++ {
// The 'select' statement allows the program to wait on multiple communication operations
// It will execute the first case that is ready, blocking the others
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
}
}
}Output
Last updated