package main
import (
"fmt"
"time"
)
// this is a worker that we will run in several parallel instances
// these workers will receive tasks through the 'jobs' channel and send the results to 'results'
// we will wait for one second for each task to simulate heavy requests
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
}
}
func main() {
// to use worker pool, we need to send a task and receive the execution results
// therefore 2 channels are created
jobs := make(chan int, 100)
results := make(chan int, 100)
// start 3 workers, initially blocked because no assignments yet
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
// send 5 jobs and then close the channel, notofying that all jobs have been sent
for j := 1; j <= 5; j++ {
jobs <- j
}
close(jobs)
// collect all the results
// this also ensures that the goroutines have ended
for a := 1; a <= 5; a++ {
<-results
}
}
This example shows how to implement a worker pool using channels and goroutines.