在 Go 语言中,waitgroup 无法满足等待一组例程中部分例程完成的需求。waitgroup 的计数器机制仅适用于等待所有例程完成,不适合特定数量或比例的例程。因此,需要替代机制来实现此功能,例如使用通道来接收每个例程完成信号。
我遇到的情况是,主要的 go 例程将创建“x”个 go 例程。但它只对要完成的“y”( y < x ) go 例程感兴趣。
我希望使用 waitgroup。但 waitgroup 只允许我等待所有 go 例程。例如,我不能这样做,
1. wg.Add (y) 2 create "x" go routines. These routines will call wg.Done() when finished. 3. wg. Wait()
当 y+1 go 例程调用 wg.done() 时,会出现恐慌,因为 wg 计数器变为负值。
我当然可以使用渠道来解决这个问题,但我对 waitgroup 是否能解决这个问题感兴趣。
解决方案
如 Adrian's answer 中所述,sync.waitgroup 是一个简单计数器,其 wait 方法将阻塞,直到计数器值达到零。它的目的是允许您在允许主执行流程继续之前阻止(或加入)多个 goroutine。
waitgroup 的界面对于您的用例来说没有足够的表现力,它的设计也不是这样的。特别是,您不能通过简单地调用 wg.add(y) (其中 y < x)来天真地使用它。第 (y+1)th goroutine 对 wg.done 的调用将为 cause a panic,因为等待组具有负内部值是一个错误。此外,我们不能通过观察waitgroup的内部计数器值来“聪明”;这会破坏抽象,并且无论如何,其内部状态都不会被导出。
实现你自己的!
您可以根据下面的代码(playground link)使用一些通道自行实现相关逻辑。从控制台观察到,有 10 个 goroutine 启动了,但是在两个完成后,我们就在 main 方法中继续执行。
package main
import (
"fmt"
"time"
)
// Set goroutine counts here
const (
// The number of goroutines to spawn
x = 10
// The number of goroutines to wait for completion
// (y <= x) must hold.
y = 2
)
func doSomeWork() {
// do something meaningful
time.Sleep(time.Second)
}
func main() {
// Accumulator channel, used by each goroutine to signal completion.
// It is buffered to ensure the [y+1, ..., x) goroutines do not block
// when sending to the channel, which would cause a leak. It will be
// garbage collected when all goroutines end and the channel falls
// out of scope. We receive y values, so only need capacity to receive
// (x-y) remaining values.
accChan := make(chan struct{}, x-y)
// Spawn "x" goroutines
for i := 0; i < x; i += 1 {
// Wrap our work function with the local signalling logic
go func(id int, doneChan chan<- struct{}) {
fmt.Printf("starting goroutine #%d\n", id)
doSomeWork()
fmt.Printf("goroutine #%d completed\n", id)
// Communicate completion of goroutine
doneChan <- struct{}{}
}(i, accChan)
}
for doneCount := 0; doneCount < y; doneCount += 1 {
<-accChan
}
// Continue working
fmt.Println("Carrying on without waiting for more goroutines")
}
避免资源泄漏
由于这不会等待 [y+1, ..., x) goroutine 完成,因此您应该在 dosomework 函数中特别小心,以消除或最小化工作无限期阻塞的风险,这也会导致导致泄漏。在可能的情况下,消除无限期阻塞 i/o(包括通道操作)或陷入无限循环的可能性。
当不再需要额外的 goroutine 的结果来让它们退出执行时,您可以使用 context 向它们发出信号。
今天关于《在Go语言中等待一组例程》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
