我们如何确保在 Goroutine 关闭之前 Channel 会读取整个缓冲区?

huangapple go评论81阅读模式
英文:

How Are We Sure That Channel Will Read The Whole Buffer Before Goroutine Closes It?

问题

我正在阅读《Go并发编程》这本书,在书中我看到了一个建议的设计模式,称为词法并发。

它的工作原理如下:

chanOwner := func() <-chan int {
	results := make(chan int, 5)
	go func() {
		defer close(results)
		for i := 0; i <= 5; i++ {
			results <- i
		}
	}()
	return results
}

consumer := func(results <-chan int) {
	for result := range results {
		fmt.Printf("Received: %d\n", result)
	}
	fmt.Println("Done receiving!")
}

results := chanOwner()
consumer(results)

我知道goroutine可以在将来的任何时间调用,所以我不明白我们如何确保在goroutine实际关闭通道之前,结果范围将读取所有缓冲区的内容。

英文:

I am reading of the book Concurrency in Go, in the book I saw a suggested design pattern, called lexical concurrency.

It is working like this:

chanOwner := func() &lt;-chan int {
	results := make(chan int, 5)
	go func() {
		defer close(results)
		for i := 0; i &lt;= 5; i++ {
			results &lt;- i
		}
	}()
	return results
}

consumer := func(results &lt;-chan int) {
	for result := range results {
		fmt.Printf(&quot;Received: %d\n&quot;, result)
	}
	fmt.Println(&quot;Done receiving!&quot;)
}

results := chanOwner()
consumer(results)

I know that a goroutine may invoke at any time in the future, so I don't understand how are we actually sure that results range will read all the buffer before goroutine actually closes the channel.

答案1

得分: 1

关闭一个通道只表示不会再向其发送新的值。通道中已经存在的值不受影响,仍然可以被消费。

英文:

closing a channel only indicates that no new values will be sent to it. the values already in the channel are unaffected and can still be consumed.

huangapple
  • 本文由 发表于 2023年5月2日 20:37:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76154911.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定