Go语言的选择(select
)可等待多个通道操作。将goroutine
和channel
与select
结合是Go语言的一个强大功能。
对于这个示例,将选择两个通道。
每个通道将在一段时间后开始接收值,以模拟阻塞在并发goroutines
中执行的RPC
操作。我们将使用select
同时等待这两个值,在每个值到达时打印它们。
执行实例程序得到的值是“one
”,然后是“two
”。注意,总执行时间只有1〜2
秒,因为1-2
秒Sleeps
同时执行。
所有的示例代码,都放在
F:\worksp\golang
目录下。安装Go编程环境请参考:http://www.yiibai.com/go/go_environment.html
select.go
的完整代码如下所示 -
package main
import "time"
import "fmt"
func main() {
// For our example we'll select across two channels.
c1 := make(chan string)
c2 := make(chan string)
// Each channel will receive a value after some amount
// of time, to simulate e.g. blocking RPC operations
// executing in concurrent goroutines.
go func() {
time.Sleep(time.Second * 1)
c1 <- "one"
}()
go func() {
time.Sleep(time.Second * 2)
c2 <- "two"
}()
// We'll use `select` to await both of these values
// simultaneously, printing each one as it arrives.
for i := 0; i < 2; i++ {
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
}
}
}
执行上面代码,将得到以下输出结果 -
F:\worksp\golang>go run select.go
received one
received two