背景
在实际工作中,我们总会限制goroutine数量—— worker pool模式,控制goroutine数量,避免goroutine泄露与膨胀
示例
package main
import (
"fmt"
"time"
)
func worker(w int, jobs int, results chanint) {
for j := range jobs {
fmt.Printf("Start task:%d, job:%d\n", w, j)
time.Sleep(time.Second)
results w * 2
fmt.Printf("End task:%d, job:%d\n", w, j)
}
}
func main() {
jobs := make(chan int, 100)
results := make(chan int, 100)
// 开启3个goroutine
for w := 0; w < 3; w++ {
go worker(w, jobs, results)
}
// 跑5个任务
for j := 0; j < 5; j++ {
jobs j
}
close(jobs)
//输出结果
for a := 0; a < 5; a++ {
tmp := results
fmt.Println(tmp)
}
}
执行
2
0
4
End task:0, job:1
End task:2, job:0
Start task:2, job:4
End task:2, job:4
End task:1, job:3
4
2
Original: https://www.cnblogs.com/kaituorensheng/p/15866063.html
Author: jihite
Title: GO worker pool
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/549042/
转载文章受原作者版权保护。转载请注明原作者出处!