Go 有一个适用于通道的 select 语句。从文档中:
select 语句让 goroutine 等待多个通信操作。
一个 select 阻塞,直到它的一个 case 可以运行,然后它执行那个 case。如果多个都准备好了,它会随机选择一个。
是否有与以下代码等效的 Python:
package main
import "fmt"
func main() {
c1 := make(chan int)
c2 := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
c1 <- i
}
quit <- 0
}()
go func() {
for i := 0; i < 2; i++ {
c2 <- i
}
}()
for {
select {
case <-c1:
fmt.Println("Received value from c1")
case <-c2:
fmt.Println("Received value from c2")
case <-quit:
fmt.Println("quit")
return
}
}
}
该程序的输出:
Received value from c1
Received value from c1
Received value from c2
Received value from c1
Received value from c2
Received value from c1
Received value from c1
Received value from c1
Received value from c1
Received value from c1
Received value from c1
Received value from c1
quit