[英]What happens when returning on for-select loop with running goroutines
I'm trying to figure how can I shorten run times as much as possible when waiting for results on multiple goroutines. 我试图弄清楚在等待多个goroutine的结果时如何尽可能缩短运行时间。 The idea is doing a for-select loop on retrieving messages from a channel (result channel) and breaking out of the loop when a result is false.
这个想法是在从通道(结果通道)中检索消息时执行一个for-select循环,并在结果为假时跳出循环。 Subsequently, potentially one or more goroutines are left running and I don't quite know what would happen in the background.
随后,可能有一个或多个goroutine处于运行状态,我不太了解后台会发生什么。
Consider this: 考虑一下:
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
}
}
}
My question is - What would happen if I return while there are goroutines trying to sent their result to the channel? 我的问题是-如果在有goroutine试图将其结果发送到通道时返回,该怎么办? I've made a buffered results channel as seen above so the goroutines wouldn't deadlock while running.
我已经创建了一个缓冲的结果通道,如上面所示,因此goroutine在运行时不会死锁。 What would happen memory-wise when doing this?
这样做会在内存方面发生什么? Will there be a goroutine leakage?
会有goroutine泄漏吗? What is the idiomatic way of doing something like this?
做这样的事情的惯用方式是什么?
This is the exact purpose behind cancellable contexts. 这是可取消上下文背后的确切目的。 Take a look at the example for
context.WithCancel
, it shows how to do exactly what you describe. 看一下
context.WithCancel
的示例,它显示了如何完全按照您的描述进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.