通道的基本发送和接收都阻塞。但是,可以使用select
和default
子句来实现非阻塞发送,接收,甚至非阻塞多路选择(select
)。
这里是一个非阻塞接收。如果消息上有可用的值,则选择将使用该值的<-message
大小写。如果不是,它会立即采用默认情况。
非阻塞发送工作类似。
可以使用多个上面的默认子句来实现多路非阻塞选择(select
)。这里尝试对消息(message
)和信号(signals
)的非阻塞接收。
所有的示例代码,都放在
F:\worksp\golang
目录下。安装Go编程环境请参考:/tutorial/detail-5562.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