[英]What happens when returning on for-select loop with running goroutines
我試圖弄清楚在等待多個goroutine的結果時如何盡可能縮短運行時間。 這個想法是在從通道(結果通道)中檢索消息時執行一個for-select循環,並在結果為假時跳出循環。 隨后,可能有一個或多個goroutine處於運行狀態,我不太了解后台會發生什么。
考慮一下:
results := make(chan bool, int NumRequests)
go DoSomething(results) // DoSomething sends the result on results channel
go DoSomething(results) // DoSomething sends the result on results channel
go DoSomething(results) // DoSomething sends the result on results channel
for {
select {
case r := <- results:
if !r {
return
}
}
}
我的問題是-如果在有goroutine試圖將其結果發送到通道時返回,該怎么辦? 我已經創建了一個緩沖的結果通道,如上面所示,因此goroutine在運行時不會死鎖。 這樣做會在內存方面發生什么? 會有goroutine泄漏嗎? 做這樣的事情的慣用方式是什么?
這是可取消上下文背后的確切目的。 看一下context.WithCancel
的示例,它顯示了如何完全按照您的描述進行操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.