50 lines
992 B
Go
50 lines
992 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// Task struct representing a task to be processed
|
|
type Task struct {
|
|
id int
|
|
}
|
|
|
|
// Worker function that processes tasks from the task channel
|
|
func worker(id int, tasks <-chan Task, wg *sync.WaitGroup) {
|
|
defer wg.Done()
|
|
for task := range tasks {
|
|
fmt.Printf("Worker %d processing task %d\n", id, task.id)
|
|
time.Sleep(time.Millisecond * 500) // Simulate work
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
const numWorkers = 3
|
|
const numTasks = 10
|
|
|
|
// Create a channel to send tasks to workers
|
|
tasks := make(chan Task, numTasks)
|
|
|
|
// Create a WaitGroup to wait for all workers to finish
|
|
var wg sync.WaitGroup
|
|
|
|
// Start worker goroutines
|
|
for i := 1; i <= numWorkers; i++ {
|
|
wg.Add(1)
|
|
go worker(i, tasks, &wg)
|
|
}
|
|
|
|
// Send tasks to the task channel
|
|
for i := 1; i <= numTasks; i++ {
|
|
tasks <- Task{id: i}
|
|
}
|
|
|
|
// Close the task channel to signal no more tasks
|
|
close(tasks)
|
|
|
|
// Wait for all workers to finish
|
|
wg.Wait()
|
|
fmt.Println("All tasks processed")
|
|
}
|