实现说明
真正干活的是函数 worker、runPool、main,其余都是接线。
本示例的循环部分是 for job := range jobs。执行扇出到 goroutine,再经 channel 交接收拢。defer 预约了清理,无论函数怎么退出,预约的调用都会触发。
使用要点
- 执行文件,
main会按顺序走完runPool。
常见问题
「基于通道的工作池」这个示例怎么运行?
直接执行即可——程序只依赖运行时自身。
主要签名是 func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup)
核心语句
func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
results <- job * job
}
}
for result := range results {
out = append(out, result)
}
for _, item := range items {
jobs <- item
}
代码示例
package main
import (
"fmt"
"sync"
)
func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
results <- job * job
}
}
func runPool(items []int, workers int) []int {
jobs := make(chan int, len(items))
results := make(chan int, len(items))
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go worker(w, jobs, results, &wg)
}
for _, item := range items {
jobs <- item
}
close(jobs)
wg.Wait()
close(results)
out := make([]int, 0, len(items))
for result := range results {
out = append(out, result)
}
return out
}
func main() {
fmt.Println(runPool([]int{1, 2, 3, 4}, 2))
}