【发布时间】:2018-02-18 20:21:48
【问题描述】:
以下代码使用 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 自行终止很重要 不再需要时。
问题是为什么这种情况会导致goroutine泄漏。在我的想法中,缓冲通道的cap是3,而3goroutines将发送他们的请求并立即退出,这不会导致泄漏。
【问题讨论】:
标签: go