Golang - 协程池 ants.NewPoolWithFunc使用介绍

前言

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


提示:以下是本篇文章正文内容,下面案例可供参考

一、功能

  • 实现了自动调度并发的goroutine,复用goroutine
  • 提供了友好的接口:任务提交、获取运行中的协程数量、动态调整协程池大小
  • 资源复用,极大节省内存使用量;在大规模批量并发任务场景下比原生goroutine并发具有更高的性能

二、安装

go get -u github.com/panjf2000/ants

使用包管理工具 glide 安装:

glide get github.com/panjf2000/ants

三、使用

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

package main

import (
	"fmt"
	"sync"
	"sync/atomic"

	"github.com/panjf2000/ants"
	"time"
)

var sum int32

func myFunc(i interface{}) error {
	n := i.(int)
	atomic.AddInt32(&sum, int32(n))
	fmt.Printf("run with %d\n", n)
	return nil
}

func demoFunc() error {
	time.Sleep(10 * time.Millisecond)
	fmt.Println("Hello World!")
	return nil
}

func main() {
	runTimes := 1000

	// use the common pool
	var wg sync.WaitGroup
	for i := 0; i < runTimes; i++ {
		wg.Add(1)
		ants.Submit(func() error {
			demoFunc()
			wg.Done()
			return nil
		})
	}
	wg.Wait()
	fmt.Printf("running goroutines: %d\n", ants.Running())
	fmt.Printf("finish all tasks.\n")

	// use the pool with a function
	// set 10 the size of goroutine pool
	p, _ := ants.NewPoolWithFunc(10, func(i interface{}) error {
		myFunc(i)
		wg.Done()
		return nil
	})
	// submit tasks
	for i := 0; i < runTimes; i++ {
		wg.Add(1)
		p.Serve(i)
	}
	wg.Wait()
	fmt.Printf("running goroutines: %d\n", p.Running())
	fmt.Printf("finish all tasks, result is %d\n", sum)
}

2.1  任务提交

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

ants.Submit(func() {})

2.2 自定义池

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

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

 2.3 动态调整协程池容量

 

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

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

该方法是线程安全的。

四、 测试性能

Benchmarks

系统参数:

OS : macOS High Sierra
Processor : 2.7 GHz Intel Core i5
Memory : 8 GB 1867 MHz DDR3

上图中的前两个 benchmark 测试结果是基于100w任务量的条件,剩下的几个是基于1000w任务量的测试结果,ants的默认池容量是5w。

  • BenchmarkGoroutine-4 代表原生goroutine

  • BenchmarkPoolGroutine-4 代表使用协程池ants

Benchmarks with Pool

Benchmarks with PoolWithFunc

吞吐量测试

10w 任务量

100w 任务量

1000w 任务量

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


使用实例:

    var stepLength int32 = 1
    var openNum int32
	const threadNumber = 100 //协程池数量

	defer ants.Release()
	var wg sync.WaitGroup
 
	p, _ := ants.NewPoolWithFunc(threadNumber, func(uid interface{}) {
		defer wg.Done()
		
		if openIdInfo == nil {
			atomic.SwapInt32(&openNum, atomic.LoadInt32(&openNum)+stepLength)
			return
		}
		
		if err != nil || message == nil {
			atomic.SwapInt32(&openNum, atomic.LoadInt32(&openNum)+stepLength)
			return
		}
	})
	if len(uidsList) > 0 {
		for _, id := range uidsList {
			wg.Add(1)
			_ = p.Invoke(id)
		}
	}
	wg.Wait()

 

 

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘贤松

一本万利

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值