天天看点

推荐很好用的Goroutine连接池

推荐很好用的Goroutine连接池

ants是一个高性能的协程池,实现了对大规模goroutine的调度管理、goroutine复用,允许使用者在开发并发程序的时候限制协程数量,复用资源,达到更高效执行任务的效果。

功能:

实现了自动调度并发的goroutine,复用goroutine

提供了友好的接口:任务提交、获取运行中的协程数量、动态调整协程池大小

资源复用,极大节省内存使用量;在大规模批量并发任务场景下比原生goroutine并发具有更高的性能

安装

1go get -u github.com/panjf2000/ants
           

使用包管理工具 glide 安装:

1glide get github.com/panjf2000/ants
           

使用

写 go 并发程序的时候如果程序会启动大量的 goroutine ,势必会消耗大量的系统资源(内存,CPU),通过使用 ants,可以实例化一个协程池,复用 goroutine ,节省资源,提升性能:

1package main
2
3import (
4    "fmt"
5    "sync"
6    "sync/atomic"
7
8    "github.com/panjf2000/ants"
9    "time"
10)
11
12var sum int32
13
14func myFunc(i interface{}) error {
15    n := i.(int)
16    atomic.AddInt32(&sum, int32(n))
17    fmt.Printf("run with %d\n", n)
18    return nil
19}
20
21func demoFunc() error {
22    time.Sleep(10 * time.Millisecond)
23    fmt.Println("Hello World!")
24    return nil
25}
26
27func main() {
28    runTimes := 1000
29
30    // use the common pool
31    var wg sync.WaitGroup
32    for i := 0; i < runTimes; i++ {
33        wg.Add(1)
34        ants.Submit(func() error {
35            demoFunc()
36            wg.Done()
37            return nil
38        })
39    }
40    wg.Wait()
41    fmt.Printf("running goroutines: %d\n", ants.Running())
42    fmt.Printf("finish all tasks.\n")
43
44    // use the pool with a function
45    // set 10 the size of goroutine pool
46    p, _ := ants.NewPoolWithFunc(10, func(i interface{}) error {
47        myFunc(i)
48        wg.Done()
49        return nil
50    })
51    // submit tasks
52    for i := 0; i < runTimes; i++ {
53        wg.Add(1)
54        p.Serve(i)
55    }
56    wg.Wait()
57    fmt.Printf("running goroutines: %d\n", p.Running())
58    fmt.Printf("finish all tasks, result is %d\n", sum)
59}
           

任务提交

提交任务通过调用 ants.Submit(func())方法:

1ants.Submit(func() {})
           

自定义池

ants支持实例化使用者自己的一个 Pool ,指定具体的池容量;通过调用 NewPool 方法可以实例化一个新的带有指定容量的 Pool ,如下:

1// set 10000 the size of goroutine pool
2p, _ := ants.NewPool(10000)
3// submit a task
4p.Submit(func() {})
           

动态调整协程池容量

需要动态调整协程池容量可以通过调用ReSize(int):

1pool.ReSize(1000) // Readjust its capacity to 1000
2pool.ReSize(100000) // Readjust its capacity to 100000
           

该方法是线程安全的。

Benchmarks

系统参数:

1OS : macOS High Sierra
2Processor : 2.7 GHz Intel Core i5
3Memory : 8 GB 1867 MHz DDR3           
推荐很好用的Goroutine连接池

BenchmarkGoroutine-4 代表原生goroutine

BenchmarkPoolGroutine-4 代表使用协程池ants

Benchmarks with Pool

推荐很好用的Goroutine连接池

Benchmarks with PoolWithFunc

推荐很好用的Goroutine连接池

吞吐量测试

10w 任务量

推荐很好用的Goroutine连接池

100w 任务量

推荐很好用的Goroutine连接池

1000w 任务量

推荐很好用的Goroutine连接池

1000w任务量的场景下,我的电脑已经无法支撑 golang 的原生 goroutine 并发,所以只测出了使用ants池的测试结果。

原文发布时间为:2018-06-27

本文来自云栖社区合作伙伴“

Golang语言社区

”,了解相关信息可以关注“

”。

继续阅读