栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

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

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 %dn", 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: %dn", 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: %dn", p.Running())
	fmt.Printf("finish all tasks, result is %dn", 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()

 

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/944275.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号