介绍
工作中常用worker pool模式, 控制go routine的数量, 防止goroutine泄露和暴涨.
DEMO
func worker(id int, jobs <- chan int, results chan <- int){
for j := range jobs{
fmt.Println("worker:%d start job:%d\n", id, j)
time.Sleep(time.Second)
fmt.Println("worker:%d end job:%d\n", id, j)
result <- j * 2
}
}
func main(){
jobs := make(chan int, 100)
results := make(chan int, 100)
//开启3个goroutine
for w := 1; w<=3 ; w++{
go worker(w, results)
}
//5个任务
for j:= 1; j<=5; j++{
job <- j
}
close(jobs)
//输出结果
for a :=1;a<=5; a++{
<- results
}
}