package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup for i := 0; i < 3; i++ { wg.Add(1) go func(num int) { defer wg.Done() fmt.Println("Worker", num, "started") // Do some work fmt.Println("Worker", num, "finished") }(i) } wg.Wait() fmt.Println("All workers done") }
package main import ( "fmt" "sync" "time" ) func main() { var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go func(num int) { defer wg.Done() fmt.Println("Worker", num, "started") time.Sleep(time.Second) fmt.Println("Worker", num, "finished") }(i) } wg.Wait() fmt.Println("All workers done") }This program is similar to the previous one, but the workers sleep for a second before finishing. The main goroutine waits for all workers to finish before printing the final message. Both examples demonstrate the use of the WaitGroup Wait method to synchronize goroutines. The package library used is the go sync package.