Go非阻塞通道操作實例

通道的基本發送和接收都阻塞。但是,可以使用selectdefault子句來實現非阻塞發送,接收,甚至非阻塞多路選擇(select)。

這裏是一個非阻塞接收。如果消息上有可用的值,則選擇將使用該值的<-message大小寫。如果不是,它會立即採用默認情況。
非阻塞發送工作類似。

可以使用多個上面的默認子句來實現多路非阻塞選擇(select)。這裏嘗試對消息(message)和信號(signals)的非阻塞接收。

所有的示例代碼,都放在 F:\worksp\golang 目錄下。安裝Go編程環境請參考:http://www.yiibai.com/go/go\_environment.html

non-blocking-channel-operations.go的完整代碼如下所示 -

package main

import "fmt"

func main() {
    messages := make(chan string)
    signals := make(chan bool)

    // Here's a non-blocking receive. If a value is
    // available on `messages` then `select` will take
    // the `<-messages` `case` with that value. If not
    // it will immediately take the `default` case.
    select {
    case msg := <-messages:
        fmt.Println("received message", msg)
    default:
        fmt.Println("no message received")
    }

    // A non-blocking send works similarly.
    msg := "hi"
    select {
    case messages <- msg:
        fmt.Println("sent message", msg)
    default:
        fmt.Println("no message sent")
    }

    // We can use multiple `case`s above the `default`
    // clause to implement a multi-way non-blocking
    // select. Here we attempt non-blocking receives
    // on both `messages` and `signals`.
    select {
    case msg := <-messages:
        fmt.Println("received message", msg)
    case sig := <-signals:
        fmt.Println("received signal", sig)
    default:
        fmt.Println("no activity")
    }
}

執行上面代碼,將得到以下輸出結果 -

F:\worksp\golang>go run non-blocking-channel-operations.go
no message received
no message sent
no activity