package main import ( "fmt" "sync" "time" ) type Job struct { ID int Payload string } func worker(id int, jobs <-chan Job, results chan<- string) { for job := range jobs { fmt.Printf("Worker %d started job %d ", id, job.ID) time.Sleep(time.Duration(job.ID%3+1) * time.Second) // Simulate work result := fmt.Sprintf("Worker %d finished job %d with payload: %s", id, job.ID, job.Payload) results <- result fmt.Printf("Worker %d finished job %d ", id, job.ID) } } func main() { const numJobs = 9 const numWorkers = 3 jobs := make(chan Job, numJobs) results := make(chan string, numJobs) var wg sync.WaitGroup // Start workers for w := 1; w <= numWorkers; w++ { wg.Add(1) go func(workerID int) { defer wg.Done() worker(workerID, jobs, results) }(w) } // Send jobs for j := 1; j <= numJobs; j++ { jobs <- Job{ID: j, Payload: fmt.Sprintf("data-%d", j)} } close(jobs) // Close jobs channel once all jobs are sent // Wait for all workers to finish processing jobs wg.Wait() close(results) // Close results channel after all workers are done // Collect and print results fmt.Println(" --- Results ---") for r := range results { fmt.Println(r) } }