package main import ( "fmt" "sync" "time" ) // simulate an expensive computation func performTask(id int) string { time.Sleep(time.Duration(id) * 100 * time.Millisecond) // Simulate work return fmt.Sprintf("Result from task %d", id) } func main() { numTasks := 5 results := make(chan string, numTasks) // Buffered channel for results var wg sync.WaitGroup for i := 1; i <= numTasks; i++ { wg.Add(1) go func(taskID int) { defer wg.Done() result := performTask(taskID) results <- result // Send result to the channel }(i) } // Wait for all tasks to complete and then close the results channel go func() { wg.Wait() close(results) }() fmt.Println("Collecting results:") // Read all results from the channel until it's closed for res := range results { fmt.Println(res) } fmt.Println("All results collected.") }