美文网首页
gobyexample-blocking-channel-ope

gobyexample-blocking-channel-ope

作者: bocsoft | 来源:发表于2018-11-07 15:17 被阅读0次

来源:https://github.com/xg-wang/gobyexample/tree/master/examples

//常规的通过通道发送和接收数据是阻塞的。然而,我们可以使用一个`default`
//子句的`select`来实现_非阻塞_的发送、接收,甚至是非阻塞的多路`select`(随机选择)
package main

import "fmt"

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

    //这是 一个非阻塞接收的例子,如果在`messagge`中存在,然后
    //`select`将这个值带入`<-messages` `case` 中,如果不是,就
    //直接到`default`分支中
    select {
    case msg := <-messages:
        fmt.Println("received message", msg)
    default:
        fmt.Println("no message received")
    }

    //非阻塞发送的例子
    msg := "hi"
    select {
    case messages <- msg:
        fmt.Println("sent message", msg)
    default:
        fmt.Println("no message sent")
    }

    //非阻塞的多路选择器,随机选择
    select {
    case msg := <-messages:
        fmt.Println("received messagge", msg)
    case sig := <-signals:
        fmt.Println("received signal", sig)
    default:
        fmt.Println("no activity")
    }

}

输出结果:

no message received
no message sent
no activity

相关文章

网友评论

      本文标题:gobyexample-blocking-channel-ope

      本文链接:https://www.haomeiwen.com/subject/wijvxqtx.html