Go Select實例

Go語言的選擇(select)可等待多個通道操作。將goroutinechannelselect結合是Go語言的一個強大功能。

對於這個示例,將選擇兩個通道。
每個通道將在一段時間後開始接收值,以模擬阻塞在併發goroutines中執行的RPC操作。我們將使用select同時等待這兩個值,在每個值到達時打印它們。

執行實例程序得到的值是「one」,然後是「two」。注意,總執行時間只有1〜2秒,因爲1-2Sleeps同時執行。

所有的示例代碼,都放在 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