Golang Go语言中 sync.WaitGroup 这样用好么
Golang Go语言中 sync.WaitGroup 这样用好么
把.Add()放到 goroutine 里面
更多关于Golang Go语言中 sync.WaitGroup 这样用好么的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
官方文档这里说的很清楚
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.
如果你是希望等待所有 goroutine 完成的话,那么 wg.Add(1)最好放到 go 函数外部, defer wg.Done() 放到函数内部
defer 没问题,但是 Add 最好放外边,虽然他在第一行,但是未必会比 wait 先执行。
不可以
这样用是错的,有可能没 Add,Wait 就执行了,起不到 Wait 的作用
我觉得不行, wait()可能直接过去,一个也等不到
这是 minikube 的源代码, 我看到的时候也是惊呆了