Wait Groups
A sync.WaitGroup is used to wait for a collection of goroutines to finish executing. The main goroutine calls Add to set the number of goroutines to wait for, and then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.
Key Points
sync.WaitGroupis used to wait for a collection of goroutines to finish.- The main goroutine calls
Add()to set the number of goroutines to wait for. - Each worker goroutine calls
Done()when it finishes. - The main goroutine calls
Wait()to block until all worker goroutines have calledDone(). WaitGroupis a simple and efficient way to synchronize the completion of a group of goroutines.
WaitGroup Example
This example shows how to use a WaitGroup to wait for a number of goroutines to complete.
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("Worker %d starting\n", id)
time.Sleep(time.Second)
fmt.Printf("Worker %d done\n", id)
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
fmt.Println("All workers done")
}Worker 1 starting
Worker 2 starting
Worker 3 starting
Worker 4 starting
Worker 5 starting
Worker 1 done
Worker 2 done
Worker 3 done
Worker 4 done
Worker 5 done
All workers doneWaitGroup Operations
| Operation | Syntax | Description |
|---|---|---|
| Declare | var wg sync.WaitGroup | Declares a new WaitGroup. |
| Add | wg.Add(n) | Increments the WaitGroup counter by n. |
| Done | wg.Done() | Decrements the WaitGroup counter by one. |
| Wait | wg.Wait() | Blocks until the WaitGroup counter is zero. |