在 Go 语言中,select 语句是一项强大的工具,用于处理并发的多个通道操作。
本文将探讨如何巧妙地使用 select 语句,通过清晰的示例代码和注释,帮助读者充分理解和灵活运用 select 切换协程的技巧。
package main import ( "fmt" "time") func main() { ch1 := make(chan string) ch2 := make(chan string) go func() { time.Sleep(2 * time.Second) ch1 <- "Channel 1" }() go func() { time.Sleep(1 * time.Second) ch2 <- "Channel 2" }() select { case msg1 := <-ch1: fmt.Println("Received from", msg1) case msg2 := <-ch2: fmt.Println("Received from", msg2) }}
package main import ( "fmt" "time") func main() { ch := make(chan string) go func() { time.Sleep(2 * time.Second) ch <- "Data received" }() select { case msg := <-ch: fmt.Println(msg) case <-time.After(1 * time.Second): fmt.Println("Timeout occurred") }}
package main import ( "fmt" "time") func main() { ch1 := make(chan string) ch2 := make(chan string) go func() { time.Sleep(2 * time.Second) ch1 <- "Data from Channel 1" }() go func() { time.Sleep(1 * time.Second) ch2 <- "Data from Channel 2" }() select { case msg1 := <-ch1: fmt.Println(msg1) case msg2 := <-ch2: fmt.Println(msg2) }}
package main import ( "fmt" "time") func main() { ch := make(chan string) go func() { time.Sleep(2 * time.Second) ch <- "Data received" }() select { case msg := <-ch: fmt.Println(msg) default: fmt.Println("No data received yet") }}
package main import ( "fmt" "time") func main() { ch1 := make(chan string) ch2 := make(chan string) go func() { for { time.Sleep(2 * time.Second) ch1 <- "Data from Channel 1" } }() go func() { for { time.Sleep(1 * time.Second) ch2 <- "Data from Channel 2" } }() for { select { case msg1 := <-ch1: fmt.Println(msg1) case msg2 := <-ch2: fmt.Println(msg2) } }}
package main import ( "fmt" "time") func main() { ch := make(chan string) stopCh := make(chan bool) go func() { for { select { case msg := <-ch: fmt.Println(msg) case <-stopCh: fmt.Println("Stopping the goroutine") return } } }() time.Sleep(3 * time.Second) stopCh <- true time.Sleep(1 * time.Second)}
package main import ( "fmt" "time") func main() { ch1 := make(chan string) ch2 := make(chan string) go func() { time.Sleep(2 * time.Second) ch1 <- "Data from Channel 1" }() go func() { time.Sleep(3 * time.Second) ch2 <- "Data from Channel 2" }() select { case msg1 := <-ch1: fmt.Println(msg1) case msg2 := <-ch2 fmt.Println(msg2) case <-time.After(1 * time.Second): fmt.Println("Timeout occurred") }}
package main import ( "fmt" "time") func main() { var ch chan string // 使用nil通道避免select阻塞 select { case data := <-ch: fmt.Println(data) default: fmt.Println("No data received") }}