Go通道缓冲实例

默认情况下,通道是未缓冲的,意味着如果有相应的接收(<- chan)准备好接收发送的值,它们将只接受发送(chan <- )。 缓冲通道接受有限数量的值,而没有用于这些值的相应接收器。

这里使一个字符串的通道缓冲多达2个值。因为这个通道被缓冲,所以可以将这些值发送到通道中,而没有相应的并发接收。

之后可以照常接收这两个值。

所有的示例代码,都放在 F:\worksp\golang 目录下。安装Go编程环境请参考:/tutorial/detail-5562.html

channel-buffering.go的完整代码如下所示 -

package main

import "fmt"

func main() {

    // Here we `make` a channel of strings buffering up to
    // 2 values.
    messages := make(chan string, 2)

    // Because this channel is buffered, we can send these
    // values into the channel without a corresponding
    // concurrent receive.
    messages <- "buffered"
    messages <- "channel"

    // Later we can receive these two values as usual.
    fmt.Println(<-messages)
    fmt.Println(<-messages)
}

执行上面代码,将得到以下输出结果 -

F:\worksp\golang>go run channel-buffering.go
buffered
channel

上一篇:Go通道实例

下一篇:Go通道同步实例

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程