worker pool也稱為thread pool,
其概念為讓固定數量的goroutine在後台運行,等待分配給它們工作,
當工作分配給worker pool時會在後台執行,而主goroutine繼續執行其他程式碼。
圖片來源:https://miro.medium.com/v2/resize:fit:4800/format:webp/1*Ya3fa36roBBhZlMl-kChXw.png
實作https://www.scaler.com/topics/golang/workerpool-in-golang/ 之範例:
package main
import (
"fmt"
"time"
)
//STEP 1
// worker function 引數: id, a jobs channel, and a results channel
func worker(id int, jobs <-chan int, results chan<- int) {
// iterates over the jobs channel
for j := range jobs {
fmt.Println("worker", id, "started job", j)
time.Sleep(time.Second)
fmt.Println("worker", id, "finished job", j)
// sends the result to the results channel
results <- j * 2
}
}
func main() {
//宣告工作數目
const numJobs = 5
//STEP 2:
// 建立 jobs channel
jobs := make(chan int, numJobs)
// 建立 results channel
results := make(chan int, numJobs)
//STEP 3:
// creates 3 goroutines for the worker function
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
//STEP 4:
// 發送工作至 jobs channel
for j := 1; j <= numJobs; j++ {
jobs <- j
}
//STEP 5:
// 關閉 jobs channel
close(jobs)
//STEP 6:
// 從 results channel接收結果
for a := 1; a <= numJobs; a++ {
<-results
}
//STEP 8:
// 關閉 results channel
close(results)
}
輸出結果:
worker 3 started job 1
worker 1 started job 2
worker 2 started job 3
worker 1 finished job 2
worker 1 started job 4
worker 3 finished job 1
worker 3 started job 5
worker 2 finished job 3
worker 1 finished job 4
worker 3 finished job 5