package main import ( "fmt" "sync" "time" ) // Task represents a unit of work. type Task struct { ID int Payload string Result chan<- string // Channel to send the result back } // worker processes tasks from the tasks channel. func worker(id int, tasks <-chan Task, wg *sync.WaitGroup) { defer wg.Done() fmt.Printf("Worker %d started. ", id) for task := range tasks { fmt.Printf("Worker %d processing task %d: %s ", id, task.ID, task.Payload) time.Sleep(time.Duration(task.ID%5+1) * 100 * time.Millisecond) // Simulate work result := fmt.Sprintf("Task %d processed by Worker %d", task.ID, id) task.Result <- result // Send result back } fmt.Printf("Worker %d stopped. ", id) } func main() { const numWorkers = 3 const numTasks = 10 tasks := make(chan Task, numTasks) // Buffered channel for tasks var wg sync.WaitGroup // Start worker goroutines for i := 1; i <= numWorkers; i++ { wg.Add(1) go worker(i, tasks, &wg) } // Submit tasks to the tasks channel results := make(chan string, numTasks) // Buffered channel for results for i := 1; i <= numTasks; i++ { tasks <- Task{ ID: i, Payload: fmt.Sprintf("Data-%d", i), Result: results, } } close(tasks) // Close the tasks channel when all tasks are submitted // Collect results from workers go func() { wg.Wait() // Wait for all workers to finish close(results) // Close the results channel after all workers are done }() for res := range results { fmt.Printf("Received result: %s ", res) } fmt.Println("All tasks processed and results collected.") }