Junior — Middle
How to implement synchronous waiting for the completion of multiple parallel tasks in a program written in Go?
sobes.tech AI
Answer from AI
In Go, sync.WaitGroup is commonly used to wait for the completion of multiple parallel tasks. It allows you to start several goroutines and wait for their completion.
Example:
package main
import (
"fmt"
"sync"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done() // Notify WaitGroup that the task is done
fmt.Printf("Worker %d started\n", id)
// simulate work
// time.Sleep(time.Second)
fmt.Printf("Worker %d finished\n", id)
}
func main() {
var wg sync.WaitGroup
numWorkers := 3
wg.Add(numWorkers) // Set the number of tasks
for i := 1; i <= numWorkers; i++ {
go worker(i, &wg)
}
wg.Wait() // Wait for all goroutines to finish
fmt.Println("All workers finished")
}
Thus, WaitGroup allows for efficient synchronization of parallel tasks.