NOTE
2.2 sync.WaitGroup
WaitGroup lets a goroutine wait for other goroutines to finish, using a counter to track outstanding work.
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
4. References
Drag to pan, scroll to zoom, and click a node to expand or collapse it. Large maps start with deeper levels collapsed; click nodes to expand them.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub