当在带有正在运行的goroutine的for-select循环中返回时会发生什么?

huangapple go评论142阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年6月28日 21:05:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/44803367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定