golang 中的 sync.WaitGroup 这样用好么

2020-07-20 15:13:11 +08:00
 hijoker
把.Add()放到 goroutine 里面

2048 次点击
所在节点    Go 编程语言
8 条回复
keepeye
2020-07-20 15:16:31 +08:00
可以的
janxin
2020-07-20 15:19:33 +08:00
官方文档这里说的很清楚

Note that calls with a positive delta that occur when the counter is zero must happen before a Wait. Calls with a negative delta, or calls with a positive delta that start when the counter is greater than zero, may happen at any time. Typically this means the calls to Add should execute before the statement creating the goroutine or other event to be waited for. If a WaitGroup is reused to wait for several independent sets of events, new Add calls must happen after all previous Wait calls have returned. See the WaitGroup example.
sunxiansong
2020-07-20 15:20:28 +08:00
如果你是希望等待所有 goroutine 完成的话,那么 wg.Add(1)最好放到 go 函数外部, defer wg.Done() 放到函数内部
Vegetable
2020-07-20 15:22:32 +08:00
defer 没问题,但是 Add 最好放外边,虽然他在第一行,但是未必会比 wait 先执行。
TypeErrorNone
2020-07-20 15:55:30 +08:00
不可以
reus
2020-07-20 19:11:56 +08:00
这样用是错的,有可能没 Add,Wait 就执行了,起不到 Wait 的作用
sxfscool
2020-07-21 08:36:56 +08:00
我觉得不行, wait()可能直接过去,一个也等不到
hijoker
2020-07-21 09:52:14 +08:00
这是 minikube 的源代码, 我看到的时候也是惊呆了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/691599

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX