NOTE

2.2 sync.WaitGroup

What sync.WaitGroup is, an example of waiting for goroutines, and its counter-based Add, Done, and Wait behavior.

GoCreated Updated 1 min readhistorical

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 counter internally
  • Add increases the counter
  • Done decrements the counter by 1
  • Wait waits until the counter reaches 0, then continues execution

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub