go语言从例子开始之Example23.通道缓冲

默认通道是 无缓冲 的,这意味着只有在对应的接收(<- chan)通道准备好接收时,才允许进行发送(chan <-)。可缓存通道允许在没有对应接收方的情况下,缓存限定数量的值。

不支持缓冲:

mk := make(chan string)
通道不支持缓存,如果进行缓冲报如下错误。
mk <- "chan"
fatal error: all goroutines are asleep - deadlock!

Example:

package main

import "fmt"



func main(){
    //使用 make(chan val-type) 创建一个新的通道。通道类型就是他们需要传递值的类型,最多缓存两个值
    mk := make(chan string, 2)

    mk <- "buf"
    mk <- "chan"
    fmt.Println(<- mk)
    fmt.Println(<- mk)
}

Result:

$ go run example.go
buf
chan

坐标: 上一个例子下一个例子