10.5 Synchronizing goroutines with WaitGroup

Synchronizing goroutines with WaitGroup

While working with concurrently running code branches, it is no exception that at some point the program needs to wait for concurrently running parts of the code. This recipe gives insight into how to use the WaitGroup to wait for running goroutines. 

同步的概念与waitgroup
在同时运行代码分支时,在某些情况下,程序还需要等待代码的并发运行部分,这也不例外。这个食谱给洞察如何使用waitgroup等待运行的概念。
package main

import "sync"
import "fmt"

func main() {
	wg := sync.WaitGroup{}
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(idx int) {
			// Do some work
			defer wg.Done()
			fmt.Printf("Exiting %d
", idx)
		}(i)
	}
	wg.Wait()
	fmt.Println("All done.")
}

/*
Exiting 9
Exiting 6
Exiting 7
Exiting 8
Exiting 3
Exiting 0
Exiting 1
Exiting 2
Exiting 4
Exiting 5
All done.
 */



With help of the  WaitGroup struct from the sync package, the program run is able to wait until some finite number of goroutines finish. The WaitGroup struct implements the method Add to add the number of goroutines to wait for. Then after the goroutine finishes,  the Done method should be called to decrement the number of goroutines to wait for. The method Wait is called as a block until the given number of Done calls has been done (usually at the end of a goroutine). The WaitGroup should be used the same way as all synchronization primitives within the sync package. After the creation of the object, the struct should not be copied.


从同步包的waitgroup结构的帮助,程序运行能够等到一些数量有限的概念完成。的waitgroup结构实现方法添加添加Goroutines数等。然后goroutine里完成后,做的方法应该被减数等概念。方法等称为块直到完成调用给定数量已经完成(通常在一个goroutine就结束)。的waitgroup应该用同样的方式为同步包内所有的同步原语。创建对象后,不应复制该结构。

原文地址:https://www.cnblogs.com/zrdpy/p/8655074.html