美文网首页
gobyexample-channel-buffering

gobyexample-channel-buffering

作者: bocsoft | 来源:发表于2018-11-04 14:28 被阅读0次

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

    // 默认情况下,通道是_无缓冲_的,这意味着只有对应的接收(`<- chan`)
    //通道准备好接受时,才允许进行发送(`chan <-`)。_可缓冲通道_
    //允许在没有对应接收方的情况下,缓存限定数量的值
    package main
    
    import "fmt"
    
    func main() {
    
        //这里我们创建了一个字符串通道,最多允许缓存2个值
        messages := make(chan string, 2)
    
        //由于此通道是缓冲的,因此我们可以将这些值发送到通道中
        //而不需要相应的并发接收
        messages <- "buffered"
        messages <- "channel"
    
        //然后我们可以像前面一样接收这两个值
        fmt.Println(<-messages)
        fmt.Println(<-messages)
    }
    
    
    

    输出结果:

    buffered
    channel
    否则会产生异常:
    fatal error: all goroutines are asleep - deadlock!
    
    goroutine 1 [chan send]:
    

    相关文章

      网友评论

          本文标题:gobyexample-channel-buffering

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