Worker Pool模式
import (
"fmt"
"sync"
"time"
)
func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
fmt.Printf("worker %d starting job %d\n", id, job)
time.Sleep(time.Second)
results <- job * 2
}
}
func main() {
const numJobs = 10
const numWorkers = 5
jobs := make(chan int, numJobs)
results := make(chan int, numJobs)
var wg sync.WaitGroup
//启动固定的worker
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go worker(i, jobs, results, &wg)
}
//发送任务
for i := 1; i < numJobs; i++ {
jobs <- i
}
close(jobs) // 有始有终,避免阻塞
go func() {
wg.Wait()
close(results) // 等待所有worker完成后关闭结果通道
}()
for result := range results {
fmt.Println("result:", result)
}
}