Go中带有缓冲通道的goroutine泄漏

问题描述:

以下代码是 Go编程语言

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) { /* ... */ }

书上说

如果我们使用了无缓冲通道,则这两个速度较慢goroutines会卡住,试图发送他们的回复在没有goroutine不会收到的频道上.这种情况称为goroutine泄漏,将是一个错误.不像垃圾变量,泄漏的goroutine不会自动收集,因此确保goroutine自身终止很重要当不再需要时.

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.


问题就是为什么这种情况会导致 goroutine 泄漏的原因.在我看来,缓冲通道的 cap 是3,而3 goroutines 将发送其请求并立即退出,这不会导致泄漏.


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.

显示的代码不会引起泄漏.

The code shown does not cause a leak.

如段落所述:

我们曾经使用过无缓冲通道

含义:如果我们使用了无缓冲通道...

Meaning: if we had used an unbuffered channel...

因此,只有在通道没有缓冲的情况下,泄漏才会发生.

So only if the channel was unbuffered the leak would occur.