golang中的add和done执行先后顺序
//代码A package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup fmt.Println(1) go wg.Done() wg.Add(1) wg.Wait() }
//代码B package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup fmt.Println(1) wg.Done() go wg.Add(1) wg.Wait() }
//代码C package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup wg.Add(3) for i := 0; i < 3; i++ { go func(i int) { fmt.Println(i) wg.Done() }(i) } wg.Wait() }
//代码D package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup for i := 0; i < 3; i++ { go func(i int) { fmt.Println(i) wg.Done() }(i) } wg.Add(3) wg.Wait() }
谁能给我解释一下done和add的执行时机?go之后执行先后顺序应该是不确定的,为什么ACD的都会稳定先执行add后执行done,代码B稳定出问题
#悬赏#