In this example we’ll look at how to implement a worker pool using goroutines and channels.
Comments from Go by Example.
In [1]:
import (
"fmt"
"time"
)
Here’s the worker, of which we’ll run several concurrent instances. These workers will receive work on the jobs channel and send the corresponding results on results. We’ll sleep a second per job to simulate an expensive task.
In [2]:
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Println("worker", id, "processing job", j)
time.Sleep(time.Second)
results <- j * 2
}
}
In order to use our pool of workers we need to send them work and collect their results. We make 2 channels for this.
In [3]:
jobs := make(chan int, 100)
results := make(chan int, 100)
Next, start up 3 workers, initially blocked because there are no jobs yet:
In [4]:
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
Send 9 jobs and then close that channel to indicate that’s all the work we have:
In [5]:
for j := 1; j <= 9; j++ {
jobs <- j
}
time.Sleep(3*time.Second)
close(jobs)
Out[5]: