英文:
goroutine leak with buffered channel in Go
问题
以下是《The Go Programming Language》中的代码:
func mirroredQuery() string {
responses := make(chan string, 3)
go func() { responses <- request("asia.gopl.io") }()
go func() { responses <- request("europe.gopl.io") }()
go func() { responses <- request("americas.gopl.io") }()
return <-responses // 返回最快的响应
}
func request(hostname string) (response string) { /* ... */ }
书中说:
如果我们使用了一个无缓冲的通道,那么两个较慢的 goroutine 将会在试图发送它们的响应到一个没有其他 goroutine 会接收的通道上而被阻塞。这种情况被称为 goroutine 泄漏,它是一个 bug。与垃圾变量不同,泄漏的 goroutine 不会自动回收,因此当不再需要时,确保 goroutine 自行终止非常重要。
问题是为什么这种情况会导致 goroutine 泄漏。在我看来,有缓冲的通道的容量是 3,3 个 goroutine 会发送它们的请求并立即退出,这不会导致泄漏。
英文:
Th following codes is in The Go Programming Language
func mirroredQuery() string {
responses := make(chan string, 3)
go func() { responses <- request("asia.gopl.io") }()
go func() { responses <- request("europe.gopl.io") }()
go func() { responses <- request("americas.gopl.io") }()
return <-responses // return the quickest response
}
func request(hostname string) (response string) { /* ... */ }
And book says
> Had we used an unbuffered channel, the two slower
> goroutines would have gotten stuck trying to send their responses
> on a channel from which no goroutine will ever receive . This situation, called a goroutine leak, would be a bug . Unlike garbage
> variables, leaked goroutines are not automatically collec ted, so
> it is important to make sure that goroutines terminate themselves
> when no longer needed.
<br/>
And the question is why this situation will cause a goroutine
leak.In my idea, the buffered channel's cap
is 3, and 3 goroutines
will send their requests and exit immediately which will not cause the leak.
答案1
得分: 4
代码显示的部分不会导致泄漏。
正如段落所述:
> 如果我们使用一个非缓冲通道
意思是:如果我们使用了非缓冲通道...
所以只有当通道是非缓冲的时候,泄漏才会发生。
英文:
The code shown does not cause a leak.
As the paragraph states:
> Had we used an unbuffered channel
Meaning: if we had used an unbuffered channel...
So only if the channel was unbuffered the leak would occur.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论