var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func(i int) { defer wg.Done() fmt.Println("Goroutine", i, "finished") }(i) } wg.Wait() fmt.Println("All goroutines finished")
var wg sync.WaitGroup for _, task := range tasks { wg.Add(1) go func(task Task) { defer wg.Done() // Do some work with the task }(task) } done := make(chan struct{}) go func() { wg.Wait() close(done) }() // Wait for either all tasks to complete or a timeout select { case <-done: fmt.Println("All tasks completed") case <-time.After(time.Second * 10): fmt.Println("Timeout exceeded") }This example uses sync.WaitGroup to wait for a collection of tasks to complete. It also uses a goroutine and a channel to implement a timeout.