示例用法sync.WaitGroup是否正确?它给出了预期的结果,但我不确定wg.Add(4)和 的位置wg.Done()。一次加四个 goroutine 有意义wg.Add()吗? 5 j( g4 G: D1 u* p( Xhttp://play.golang.org/p/ecvYHiie0P$ t6 a0 p) A. E. e0 T# |3 t
package mainimport "fmt" "sync" "time")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")} 8 _8 z. ~9 ] e4 P9 R1 {% X
结果(如预期): , K' o q* c; \9 V4 l5 Q0 S2 A. f0 n
Function in background,duration: 150msFunction in background,duration: 200msFunction in background,duration: 400msFunction in background,duration: 600msDone, C# v4 }9 S) v2 ?/ l4 N
& h' Q# j+ ?0 N; J 解决方案: # S9 K+ d' T, W5 e$ R 是的,这个例子是正确的。句子很重要wg.Add()以前发生过go防止竞争条件。以下也是正确的:) O9 S0 Y8 E- A6 ? \9 P. O3 O/ E) @
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")} 8 ^; a7 W) n* R9 F3 f