golang线程池ants-四种使用方法

devtools/2024/9/20 9:18:42/ 标签: golang, 后端, 多线程

目录

1、ants介绍

2、使用方式汇总

3、各种使用方式详解

3.1 默认池

3.2 普通模式

3.3 带参函数

3.4 多池多协程

4、总结


1、ants介绍

      众所周知,goroutine相比于线程来说,更加轻量、资源占用更少、无线程上下文切换等优势,但是也不能无节制的创建使用,如果系统中开启的goroutine过多而没有及时回收,也会造成系统内存资源耗尽。

      ants是一款高性能的协程管理池,实现了协程的创建、缓存、复用、刷新、停止能功能,同时允许开发者设置线程池中worker的数量、线程池本身的个数以及workder中的任务,从而实现更加高效的运行效果。

github:GitHub - panjf2000/ants: 🐜🐜🐜 ants is a high-performance and low-cost goroutine pool in Go./ ants 是一个高性能且低损耗的 goroutine 池。

2、使用方式汇总

ants的使用有四种方式,分别如下:

这四种使用方式,前两种最常用,基本能满足日常系统的开发需要,第四种默认池,简单的场景也可以用,但不推荐,多池的情况还没想到特别合适的应用场景。

3、各种使用方式详解

3.1 默认池

ants在启动时,会默认初始化一个协程池,这部分代码位于ants.go文件中:

var (// ErrLackPoolFunc will be returned when invokers don't provide function for pool.ErrLackPoolFunc = errors.New("must provide function for pool")// ErrInvalidPoolExpiry will be returned when setting a negative number as the periodic duration to purge goroutines.ErrInvalidPoolExpiry = errors.New("invalid expiry for pool")// ErrPoolClosed will be returned when submitting task to a closed pool.ErrPoolClosed = errors.New("this pool has been closed")// ErrPoolOverload will be returned when the pool is full and no workers available.ErrPoolOverload = errors.New("too many goroutines blocked on submit or Nonblocking is set")// ErrInvalidPreAllocSize will be returned when trying to set up a negative capacity under PreAlloc mode.ErrInvalidPreAllocSize = errors.New("can not set up a negative capacity under PreAlloc mode")// ErrTimeout will be returned after the operations timed out.ErrTimeout = errors.New("operation timed out")// ErrInvalidPoolIndex will be returned when trying to retrieve a pool with an invalid index.ErrInvalidPoolIndex = errors.New("invalid pool index")// ErrInvalidLoadBalancingStrategy will be returned when trying to create a MultiPool with an invalid load-balancing strategy.ErrInvalidLoadBalancingStrategy = errors.New("invalid load-balancing strategy")// workerChanCap determines whether the channel of a worker should be a buffered channel// to get the best performance. Inspired by fasthttp at// https://github.com/valyala/fasthttp/blob/master/workerpool.go#L139workerChanCap = func() int {// Use blocking channel if GOMAXPROCS=1.// This switches context from sender to receiver immediately,// which results in higher performance (under go1.5 at least).if runtime.GOMAXPROCS(0) == 1 {return 0}// Use non-blocking workerChan if GOMAXPROCS>1,// since otherwise the sender might be dragged down if the receiver is CPU-bound.return 1}()// log.Lmsgprefix is not available in go1.13, just make an identical value for it.logLmsgprefix = 64defaultLogger = Logger(log.New(os.Stderr, "[ants]: ", log.LstdFlags|logLmsgprefix|log.Lmicroseconds))// Init an instance pool when importing ants.defaultAntsPool, _ = NewPool(DefaultAntsPoolSize)
)

使用起来就比较简单了,直接往池子里提交任务即可。

package mainimport ("fmt""sync""time""github.com/panjf2000/ants/v2"
)func add(d int) {sum := 0for i := 0; i < d; i++ {sum += i}
}
func main() {var wg sync.WaitGroupnow := time.Now()for i := 0; i < 5; i++ {wg.Add(1)ants.Submit(func() {add(10000000000)wg.Done()})}wg.Wait()fmt.Println(time.Since(now))now = time.Now()for i := 0; i < 5; i++ {add(10000000000)}fmt.Println(time.Since(now))
}

运行结果:

3.2 普通模式

普通模式和使用默认池非常类似,但是需要自己创建一个线程池:

p, _ := ants.NewPool(5)

函数参数为协程池协程个数,测试代码如下:

package mainimport ("fmt""sync""time""github.com/panjf2000/ants/v2"
)func add(d int) {sum := 0for i := 0; i < d; i++ {sum += i}
}
func main() {var wg sync.WaitGroupnow := time.Now()p, _ := ants.NewPool(5)for i := 0; i < 5; i++ {wg.Add(1)p.Submit(func() {add(10000000000)wg.Done()})}wg.Wait()fmt.Println("协程池运行:", time.Since(now))now = time.Now()for i := 0; i < 5; i++ {add(10000000000)}fmt.Println("循环运行:", time.Since(now))
}

3.3 带参函数

带参函数,重点是往worker中传递函数执行的参数,每个workder中都是同一个执行函数。

package mainimport ("fmt""sync""time""github.com/panjf2000/ants/v2"
)func add(d int) {sum := 0for i := 0; i < d; i++ {sum += i}fmt.Println("the sum is: ", sum)
}
func main() {var wg sync.WaitGroupnow := time.Now()p, _ := ants.NewPoolWithFunc(5, func(i interface{}) {add(i.(int))wg.Done()})for i := 0; i < 5; i++ {wg.Add(1)p.Invoke(1000000000)}wg.Wait()fmt.Println("循环运行:", time.Since(now))
}

运行结果:

liupeng@liupengdeMacBook-Pro ants_study % go run thread_default.go
the sum is:  499999999500000000
the sum is:  499999999500000000
the sum is:  499999999500000000
the sum is:  499999999500000000
the sum is:  499999999500000000
循环运行: 352.447333ms

3.4 多池多协程

这种模式,就是声明了多个协程池,每个池子里有多个协程在跑。

package mainimport ("fmt""sync""time""github.com/panjf2000/ants/v2"
)func add(d int) {sum := 0for i := 0; i < d; i++ {sum += i}fmt.Println("the sum is: ", sum)
}
func main() {var wg sync.WaitGrouprunTimes := 20now := time.Now()mpf, _ := ants.NewMultiPoolWithFunc(10, runTimes/10, func(i interface{}) {add(i.(int))wg.Done()}, ants.LeastTasks)for i := 0; i < runTimes; i++ {wg.Add(1)mpf.Invoke(1000000000)}wg.Wait()fmt.Println("循环运行:", time.Since(now))
}

运行记录:

4、总结

     以上就是ants协程池所有的使用方式,3.2、3.3章节介绍的两种方式比较常用,也是推荐的使用方式,使用协程池,可以有效的控制系统硬件资源的使用,防止机器被打满,对于高并发服务非常推荐使用。

      后面会学习一下ants的源码,并整理成文档发出来,欢迎围观。


http://www.ppmy.cn/devtools/46767.html

相关文章

AI推介-大语言模型LLMs论文速览(arXiv方向):2024.05.01-2024.05.05

文章目录~ 1.Sub-goal Distillation: A Method to Improve Small Language Agents2.Beyond Performance: Quantifying and Mitigating Label Bias in LLMs3.Recall Them All: Retrieval-Augmented Language Models for Long Object List Extraction from Long Documents4.CoE-S…

lua字符串模式匹配

string.gmatch()不支持匹配首字符 string.gmatch(s, pattern)中&#xff0c;如果s的开头是’^字符&#xff0c;不会被当成首字符标志&#xff0c;而是被当成一个普通字符。 比如 s"hello world from lua" for w in string.gmatch(s, "^%a") doprint(w) e…

Pytorch常用函数用法归纳:Tensor张量之间的计算

1.torch.add() (1)函数原型: torch.add(input, other, alpha, out) (2)参数说明: 参数名称参数类型参数说明inputtorch.Tensor表示参与运算的第一个输入Tensor张量othertorch.Tensor或者Number表示参与运算的第二个输入Tensor张量或标量alphaNumber, optional一个可选的缩放…

centos系统上新建用户

目录 新建用户 设置密码 给予sudo权限 切换到新用户 新建用户 adduser 用户名 设置密码 passwd 用户名 给予sudo权限 usermod -aG wheel 用户名 切换到新用户 su 用户名

cocos creator 3.x实现手机虚拟操作杆

简介 在许多移动游戏中&#xff0c;虚拟操纵杆是一个重要的用户界面元素&#xff0c;用于控制角色或物体的移动。本文将介绍如何在Unity中实现虚拟操纵杆&#xff0c;提供了一段用于移动控制的代码。我们将讨论不同类型的虚拟操纵杆&#xff0c;如固定和跟随&#xff0c;以及如…

关于焊点检测SJ-BIST)模块实现

关于焊点检测SJ-BIST)模块实现 语言 :Verilg HDL 、VHDL EDA工具:ISE、Vivado、Quartus II 关于焊点检测SJ-BIST)模块实现一、引言二、焊点检测功能的实现方法(1) 输入接口(2) 输出接口(3) 模块实现核心状态图(4) 模块实现原理图关键词: Verilog HDL,焊点检测功能…

充电桩软硬件,赚钱新招数!-慧哥充电桩开源系统

慧哥充电桩开源平台V2.5.2_----- SpringCloud 汽车 电动自行车 云快充1.5、云快充1.6 https://liwenhui.blog.csdn.net/article/details/134773779?spm1001.2014.3001.5502 充电桩软件和硬件一体化的盈利方向可以清晰地归纳为以下几个主要方面&#xff1a; 充电服务收费&…

科技与环保

科技与环保之间存在着密不可分的关系&#xff0c;两者相互影响、相互促进&#xff0c;共同推动着社会的可持续发展。以下是对科技与环保关系的详细分析&#xff1a; 一、科技进步对环保的积极作用 提供技术手段和解决方案&#xff1a;科技进步为环境保护提供了强有力的技术支…

gitlab服务器迁移(亲测有效)

描述&#xff1a;最近公司迁移gitlab&#xff0c;我没有迁移过&#xff0c;经过网上查找资料最终完成迁移&#xff0c;途中也遇到挺多坑和两个问题&#xff0c;希望能帮到你。 新服务器安装gitlab 注意&#xff1a;新服务器gitlab版本也需要和旧版本一致。 首先查看原Gitlab…

基于EasyX的贪吃蛇小游戏 - C语言

游戏基本功能演示&#xff1a; 1.主菜单界面 2.自定难度界面 在这里可以自行设定游戏的难度&#xff0c;包括蛇的移动速度&#xff0c;初始节数&#xff0c;以及默认模式&#xff0c;参考线&#xff08;网格&#xff09;。这些设定的数据都会在右上角的游戏属性栏中实时显示。…

线程池的使用

线程池 一、Java线程池介绍 在Java中&#xff0c;线程池是一种管理和复用线程的机制&#xff0c;用于提高多线程应用程序的性能和资源利用率。线程池在执行任务时&#xff0c;可以避免频繁地创建和销毁线程&#xff0c;从而减少了系统开销&#xff0c;并且能够更有效地利用系统…

2025 QS 世界大学排名公布,北大清华跻身全球前20

一年一度&#xff0c;2025 QS 世界大学排名公布&#xff01; QS&#xff08;Quacquarelli Symonds&#xff09;是唯一一个同时将就业能力与可持续发展纳入评价体系的排名。 继去年 2024 QS 排名因为“墨尔本超耶鲁&#xff0c;新南悉尼高清华”而荣登微博热搜之后&#xff0c…

windows10 安装子linux系统(WSL安装方式)

在 windows 10 平台采用了WSL安装方式安装linux子系统 1 查找自己想要安装的linux子系统 wsl --list --online 2 在线安装 个人用Debian比较多&#xff0c;这里选择Debian&#xff0c;如下图&#xff1a; wsl --install -d Debian 安装完成&#xff0c;如下&#xff1a; 相关…

K8s:Pod初识

Pod Pod是k8s处理的最基本单元。容器本身不会直接分配到主机上&#xff0c;封装为Pod对象&#xff0c;是由一个或多个关系紧密的容器构成。她们共享 IPC、Network、和UTS namespace pod的特征 包含多个共享IPC、Network和UTC namespace的容器&#xff0c;可直接通过loaclhos…

AI视频教程下载:给初学者的ChatGPT提示词技巧

你是否厌倦了花费数小时在可以通过强大的语言模型自动化的琐碎任务上&#xff1f;你是否准备好利用 ChatGPT——世界上最先进的语言模型——并将你的生产力提升到下一个水平&#xff1f; ChatGPT 是语言处理领域的游戏规则改变者&#xff0c;它能够理解并响应自然语言&#xf…

AndroidStudio中debug.keystore的创建和配置使用

1.如果没有debug.keystore,可以按照下面方法创建 首先在C:\Users\Admin\.android路径下打开cmd窗口 之后输入命令:keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -keyalg RSA -validity 10000 输入两次密码(密码不可见,打码处随便填写没关系) 2.在build…

JVM的内存结构

JVM 内存结构 方法区: 方法区主要用于存储虚拟机加载的类信息、常量、静态变量&#xff0c;以及编译器编译后的代码等数据。 程序计数器 由于在JVM中&#xff0c;多线程是通过线程轮流切换来获得CPU执行时间的&#xff0c;因此&#xff0c;在任一具体时刻&#xff0c;一个CP…

VB.net 进行CAD二次开发(二)

利用参考文献2&#xff0c;添加面板 执行treeControl New UCTreeView()时报一个错误&#xff1a; 用户代码未处理 System.ArgumentException HResult-2147024809 Message控件不支持透明的背景色。 SourceSystem.Windows.Forms StackTrace: 在 System.Windows…

为什么身份控制是确保API接口访问安全的关键?

您使用过授权流程吗&#xff1f;你输入过 PIN 码访问账户吗&#xff1f;如果用过&#xff0c;你就已经熟悉身份控制了。 身份控制对于正确监控和保护网络的各个方面&#xff08;包括API&#xff09;至关重要。它对于保持高效的工作流程并确保安全也至关重要。在当今竞争激烈、…

Java基础27,28(多线程,ThreadMethod ,线程安全问题,线程状态,线程池)

目录 一、多线程 1. 概述 2. 进程与线程 2.1 程序 2.2 进程 2.3 线程 2.4 进程与线程的区别 3. 线程基本概念 4.并发与并行 5. 线程的创建方式 方式一&#xff1a;继承Thread类 方式二&#xff1a;实现Runable接口 方式三&#xff1a;实现Callable接口 方式四&…