func performTask(wg *sync.WaitGroup) { defer wg.Done() // perform some task } func main() { var wg sync.WaitGroup wg.Add(3) // spawn 3 goroutines to perform tasks for i := 0; i < 3; i++ { go performTask(&wg) } wg.Wait() // all tasks have completed }
func performTask(wg *sync.WaitGroup, ch chan int) { defer wg.Done() // perform some task ch <- 1 } func main() { var wg sync.WaitGroup ch := make(chan int, 3) wg.Add(3) // spawn 3 goroutines to perform tasks for i := 0; i < 3; i++ { go performTask(&wg, ch) } go func() { wg.Wait() close(ch) }() // range over channel to receive completion signals for range ch { // task has completed } }In this example, we create a WaitGroup and add 3 to the counter. We also create a buffered channel with a capacity of 3. We then spawn 3 goroutines to perform some task, passing both the WaitGroup pointer and the channel as arguments. Each goroutine will decrement the counter using `wg.Done()` once the task is complete, and will also write to the channel to signal completion. We then create a new goroutine that waits for all tasks to complete using `wg.Wait()`, and then closes the channel. Finally, we range over the channel to receive completion signals. The sync WaitGroup is part of the standard library in Go, and is located in the `sync` package.