gpt4 book ai didi

Go中带有缓冲 channel 的goroutine泄漏

转载 作者:IT王子 更新时间:2023-10-29 02:32:16 27 4
gpt4 key购买 nike

以下代码是 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) { /* ... */ }

书上说

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泄漏。我的想法是buffered channel的cap是3,3个 goroutines 将发送他们的请求并立即退出,这不会导致泄漏。

最佳答案

显示的代码不会导致泄漏。

如段落所述:

Had we used an unbuffered channel

含义:如果我们使用了一个无缓冲的 channel ...

所以只有当 channel 没有缓冲时才会发生泄漏。

关于Go中带有缓冲 channel 的goroutine泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46141353/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com