Go 语言的并发编程模型以其简洁而强大的 goroutine 为特色。
而 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 <- "goroutine 1 completed" }() go func() { time.Sleep(1 * time.Second) ch2 <- "goroutine 2 completed" }() select { case res := <-ch1: fmt.Println(res) case res := <-ch2: fmt.Println(res) }}
package main import ( "fmt" "time") func main() { ch := make(chan string) go func() { time.Sleep(2 * time.Second) ch <- "goroutine completed" }() select { case res := <-ch: fmt.Println(res) case <-time.After(1 * time.Second): fmt.Println("Timeout: goroutine not completed within 1 second") }}
package main import ( "fmt" "time") func main() { ch1 := make(chan string) ch2 := make(chan string) go func() { time.Sleep(2 * time.Second) ch1 <- "goroutine 1 completed" }() go func() { time.Sleep(1 * time.Second) ch2 <- "goroutine 2 completed" }() for i := 0; i < 2; i++ { select { case res := <-ch1: fmt.Println(res) case res := <-ch2: fmt.Println(res) } }}
package main import ( "fmt" "time") func main() { ch := make(chan string) select { case res := <-ch: fmt.Println(res) default: fmt.Println("No communication yet") } go func() { time.Sleep(1 * time.Second) ch <- "goroutine completed" }() time.Sleep(2 * time.Second)}
package main import ( "fmt" "time") func main() { ch1 := make(chan string) ch2 := make(chan string) select { case res := <-ch1: fmt.Println(res) case res := <-ch2: fmt.Println(res) default: fmt.Println("No communication yet") } go func() { time.Sleep(2 * time.Second) ch1 <- "goroutine 1 completed" }() 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 <- "goroutine 1 completed" }() go func() { time.Sleep(1 * time.Second) ch2 <- "goroutine 2 completed" }() for i := 0; i < 2; i++ { select { case res := <-ch1: fmt.Println(res) case res := <-ch2: fmt.Println(res) } }}
总结
通过本文的讨论和示例代码,对如何使用 select 切换协程有了更深入的理解。
select 是 Go 语言并发编程中的一项强大工具,掌握其使用技巧将有助于读者更好地处理并发场景,提高代码的可读性和可维护性。
在实际项目中,善用 select 将使你的并发代码更加优雅而高效。