英文:
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() <-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)
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论