- Define a function that represents the worker. This function should receive tasks from a channel and process them.
- Create a buffered channel to hold the tasks that need to be executed.
- Launch a fixed number of goroutines (workers) that will listen for tasks on the channel and execute them.
- Send tasks to the channel for the workers to process.
- Use synchronization mechanisms, such as
sync.WaitGroup
, to ensure that all tasks are completed before the program exits.
Worker Pools
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Println("worker", id, "started job", j)
time.Sleep(time.Second)
fmt.Println("worker", id, "finished job", j)
results <- j * 2
}
}