NOTE
2.2 sync.WaitGroup
What sync.WaitGroup is, an example of waiting for goroutines, and its counter-based Add, Done, and Wait behavior.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What It Is
A way to control concurrency. It lets one goroutine wait for other goroutines to finish. It is similar to 9.CountDownLatch.md.
2. Usage
func main() {
var wg sync.WaitGroup
wg.Add(2)
go func() {
time.Sleep(2*time.Second)
fmt.Println("No. 1 finished")
wg.Done()
}()
go func() {
time.Sleep(2*time.Second)
fmt.Println("No. 2 finished")
wg.Done()
}()
wg.Wait()
fmt.Println("All right, everyone is done. Time to finish work")
}
3. Implementation
- It maintains a
counterinternally Addincreases the counterDonedecrements the counter by 1Waitwaits until the counter reaches 0, then continues execution
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub