waitGroup 从字面上来看是等待组,好处是主线程的退出或执行需要其之前所有 goroutine 执行完毕才回到主线程执行,这是保证所有的 goroutine 都会被执行到
···
import (
"fmt"
"time"
"sync"
)
func doSomething(millisecs time.Duration, wg *sync.WaitGroup){
duration := millisecs * time.Millisecond
time.Sleep(duration)
fmt.Println("Function in background, duration:", duration)
wg.Done()
}
func main(){
var wg sync.WaitGroup
wg.Add(4)
go doSomething(200, &wg)
go doSomething(400, &wg)
go doSomething(150, &wg)
go doSomething(600, &wg)
wg.Wait()
fmt.Println("Done")
}
为发生我们添加多余 wg 造成 deadlock 好的的喜欢写一个 goroutine 就 Add 一次。
func main(){
var wg sync.WaitGroup
wg.Add(1)
go dosomething(200, &wg)
wg.Add(1)
go dosomething(400, &wg)
wg.Add(1)
go dosomething(150, &wg)
wg.Add(1)
go dosomething(600, &wg)
wg.Wait()
fmt.Println("Done")
}
Function in background, duration: 150ms
Function in background, duration: 200ms
Function in background, duration: 400ms
Function in background, duration: 600ms
Done
如果我们 wg.Add 数量超出了现有 goroutine 个数就会发生 deadlock! 错误
wg.Add(5)
fatal error: all goroutines are asleep - deadlock!
有疑问加站长微信联系(非本文作者)