天天看點

推薦很好用的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語言社群

”,了解相關資訊可以關注“

”。

繼續閱讀