golang 使用 select 避免阻塞 示范
时间: 2023-11-12 13:07:42 浏览: 30
好的,下面是一个示范:
```go
package main
import (
"fmt"
"time"
)
func main() {
ch1 := make(chan int)
ch2 := make(chan int)
go func() {
for {
ch1 <- 1
time.Sleep(time.Second)
}
}()
go func() {
for {
ch2 <- 2
time.Sleep(time.Second)
}
}()
for {
select {
case num := <-ch1:
fmt.Println("Received from ch1:", num)
case num := <-ch2:
fmt.Println("Received from ch2:", num)
default:
fmt.Println("No data received")
time.Sleep(time.Second)
}
}
}
```
这个示例中,创建了两个 channel(ch1 和 ch2),分别在两个 goroutine 中向其中发送数据。在主函数中,使用 select 语句监听这两个 channel 的数据,当其中一个 channel 有数据时,就接收并处理,如果没有数据,则执行 default 分支。这样可以避免程序因为阻塞在某个 channel 上而无法继续执行。