缓冲通道在达到其容量时不会阻塞写入

https://play.golang.org/p/5A-dnZVy2aA


func closeChannel(stream chan int) {

    fmt.Println("closing the channel")

    close(stream)

}


func main() {

    chanOwner := func() <-chan int {

        resultStream := make(chan int, 5)

        go func() {

            defer closeChannel(resultStream)

            for i := 0; i <= 5; i++ {

                resultStream <- i

            }

        }()

        return resultStream

    }

    resultStream := chanOwner()

    for result := range resultStream { //this blocks until the channel is closed

        fmt.Printf("Received: %d\n", result)

    }

    fmt.Println("done receiving")

}

程序输出


closing the channel

Received: 0

Received: 1

Received: 2

Received: 3

Received: 4

Received: 5

done receiving

为什么在上述程序中的closing the channel任何语句之前打印语句。Received由于通道的缓冲容量为 5,并且我们正在向其中插入 6 个元素,因此我希望它在resultStream <- i读取值并清除缓冲区中的空间之前阻塞。


慕勒3428872
浏览 84回答 1
1回答

茅侃侃

生成器 goroutine 将通道填充到其容量并阻塞。循环的接收器从通道接收第一项,这再次启用生成器 goroutine。Received生成器 goroutine 在接收器 for 循环打印消息之前运行完成,打印closing the channel消息。然后接收器循环接收所有剩余的消息。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go