英文:
What happens when returning on for-select loop with running goroutines
问题
我正在尝试弄清楚在等待多个goroutine的结果时如何尽量缩短运行时间。我的想法是在一个for-select循环中从通道(结果通道)中检索消息,并在结果为false时跳出循环。随后,可能会有一个或多个goroutine仍在运行,我不太清楚后台会发生什么。
考虑以下代码:
results := make(chan bool, int NumRequests)
go DoSomething(results) // DoSomething将结果发送到results通道
go DoSomething(results) // DoSomething将结果发送到results通道
go DoSomething(results) // DoSomething将结果发送到results通道
for {
select {
case r := <- results:
if !r {
return
}
}
}
我的问题是:如果在还有goroutine尝试将其结果发送到通道时我就返回了,会发生什么?如上所示,我已经创建了一个带缓冲区的results通道,以防止goroutine在运行时发生死锁。这样做会在内存方面有什么影响?会有goroutine泄漏吗?有没有惯用的方法来处理这种情况?
英文:
I'm trying to figure how can I shorten run times as much as possible when waiting for results on multiple goroutines. 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. Subsequently, potentially one or more goroutines are left running and I don't quite know what would happen in the background.
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? I've made a buffered results channel as seen above so the goroutines wouldn't deadlock while running. What would happen memory-wise when doing this? Will there be a goroutine leakage? What is the idiomatic way of doing something like this?
答案1
得分: 5
这就是可取消上下文的确切目的。看一下context.WithCancel
的示例,它展示了如何实现你所描述的功能。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论