引言
很多时候,还是需要用到协程池的,尤其是控制并发速度,如果并发速度过大,导致本地机器卡死,或者服务器扛不住流量,会崩掉。
1. 安装
github https://github.com/pkufergus
go get github.com/pkufergus/goroutinepool
2. 使用
2.1 创建协程池
import (
"github.com/pkufergus/goroutinepool"
"time"
"fmt"
)
// 设定协程池的中协程的数量是30个
p := utils.NewGPool(30)
示例
package main
import (
"github.com/pkufergus/goroutinepool"
"time"
"fmt"
)
func main() {
p := goroutinepool.NewRoutinePool(10)
for i := 0; i < 100; i++ {
count := i
p.AddJob(func() {
time.Sleep(1000 * time.Millisecond)
fmt.Printf("%d\n", count)
})
}
p.WaitAll()
}
致谢
程序的API形式