加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang noblocking send

发布时间:2020-12-16 18:21:12 所属栏目:大数据 来源:网络整理
导读:// Basic sends and receives on channels are blocking.// However,we can use `s elect ` with a `d efault ` clause to// implement _non-blocking_ sends,receives, and even// non-blocking multi-way `s elect `s .package mainimport "fmt" func main
// Basic sends and receives on channels are blocking.
// However,we can use `select` with a `default` clause to
// implement _non-blocking_ sends,receives,and even
// non-blocking multi-way `select`s.

package main

import "fmt"

func main() {
    messages := make(chan string,1)
    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")
    }
}

若messages没有设置buffer size的话,那么messages <- msg是发送不出去的

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读