// go第三方库文档 线程池ants
// https://pkg.go.dev/github.com/panjf2000/ants/v2// 想象一下,你的程序启动了大量的goroutine,导致了巨大的内存消耗。为了缓解这种情况,您只需导入ants包并将所有任务提交到具有固定容量的默认池中,该池在导入ants包时激活:
package mainimport ("fmt""sync""sync/atomic""time""github.com/panjf2000/ants/v2"
)var sum int32func myFunc(i interface{}) {n := i.(int32)atomic.AddInt32(&sum, n)fmt.Printf("run with %d\n", n)
}func demoFunc() {time.Sleep(10 * time.Millisecond)fmt.Println("Hello World!")
}func main() {defer ants.Release()runTimes := 1000//使用公共池。var wg sync.WaitGroupsyncCalculateSum := func() {demoFunc()wg.Done()}for i := 0; i < runTimes; i++ {wg.Add(1)_ = ants.Submit(syncCalculateSum)}wg.Wait()fmt.Printf("running goroutines: %d\n", ants.Running())fmt.Printf("finish all tasks.\n")//将池与函数一起使用,//将goroutine池的容量设置为10,过期时间设置为1秒。p, _ := ants.NewPoolWithFunc(10, func(i interface{}) {myFunc(i)wg.Done()})defer p.Release()//逐个提交任务。for i := 0; i < runTimes; i++ {wg.Add(1)_ = p.Invoke(int32(i))}wg.Wait()fmt.Printf("running goroutines: %d\n", p.Running())fmt.Printf("finish all tasks, result is %d\n", sum)
}Functional options for ants pool
//选项表示可选函数。
type Option func(opts *Options)//Options包含实例化ants池时将应用的所有选项。
type Options struct {//过期时间是清道夫goroutine清理那些过期工人的时间,//清道夫会在每个“过期”期间扫描所有工人,并清理那些没有被清除的工人//用于超过“呼气时间”。ExpiryDuration time.Duration//PreAlloc指示初始化池时是否进行内存预分配。PreAlloc bool//pool.Submit上阻止goroutine的最大数目。//0(默认值)表示没有此类限制。MaxBlockingTasks int//当Nonblocking为true时,Pool.Submit将永远不会被阻止。//无法立即完成Pool.Submit时,将返回ErrPoolOverload。//当非阻塞为真时,MaxBlockingTasks不工作。Nonblocking bool//PanicHandler用于处理来自每个worker goroutine的恐慌。//如果为零,恐慌将再次从工人的狂欢中消失。PanicHandler func(interface{})//Logger是用于记录信息的自定义记录器,如果未设置,//使用日志包中的默认标准记录器。Logger Logger
}//WithOptions接受整个选项配置。
func WithOptions(options Options) Option {return func(opts *Options) {*opts = options}
}//WithExpiryDuration设置清理GoRoutine的间隔时间。
func WithExpiryDuration(expiryDuration time.Duration) Option {return func(opts *Options) {opts.ExpiryDuration = expiryDuration}
}
//WithPreAlloc表示是否应为工作人员使用malloc。
func WithPreAlloc(preAlloc bool) Option {return func(opts *Options) {opts.PreAlloc = preAlloc}
}//WithMaxBlockingTasks设置当GoRoutine达到池容量时被阻止的最大GoRoutine数。
func WithMaxBlockingTasks(maxBlockingTasks int) Option {return func(opts *Options) {opts.MaxBlockingTasks = maxBlockingTasks}
}//WithNonblocking表示当没有可用的工作线程时,池将返回nil。
func WithNonblocking(nonblocking bool) Option {return func(opts *Options) {opts.Nonblocking = nonblocking}
}//WithPanicHandler设置紧急处理程序。
func WithPanicHandler(panicHandler func(interface{})) Option {return func(opts *Options) {opts.PanicHandler = panicHandler}
}//WithLogger设置自定义记录器。
func WithLogger(logger Logger) Option {return func(opts *Options) {opts.Logger = logger}
}
// options包含ants池的所有可选配置,它允许您通过调用option函数在NewPool/NewPoolWithFuncmethod中设置每个配置来自定义goroutine池。Customize limited pool
// ants还支持自定义池的容量。您可以调用NewPool方法来实例化具有给定容量的池,如下所示:
//将10000设置为goroutine池的大小
p, _ := ants.NewPool(10000)Submit tasks
// 可以通过调用ants.Submit(func())提交任务
ants.Submit(func(){})Tune pool capacity in runtime
// 您可以使用tune(int)在运行时调整ants池的容量:
Tune(1000)//将其容量调整为1000
Tune(100000)//将其容量调整为100000
// 在这种情况下,不要担心同步问题,这里的方法是线程安全的(或者应该称为goroutine-safe)。Pre-malloc goroutine queue in pool
// ants允许您在池中预先分配goroutine队列的内存,在某些特殊情况下,例如需要超大容量池的场景下,这可能会提高性能,同时goroutine中的每个任务都会持续很长时间,在这种情况下,预mallocing将减少goroutine队列中的大量内存分配。
//当您调用此方法时,ants将预先分配池的全部容量
p, _ := ants.NewPool(100000, ants.WithPreAlloc(true))Release Pool
pool.Release()Reboot Pool
//调用Reboot()后,已释放的池仍可使用。
pool.Reboot()func Cap() int
func Free() int
func Reboot()
func Release()
func Running() int
func Submit(task func()) error
type Logger
type Option
func WithExpiryDuration(expiryDuration time.Duration) Option
func WithLogger(logger Logger) Option
func WithMaxBlockingTasks(maxBlockingTasks int) Option
func WithNonblocking(nonblocking bool) Option
func WithOptions(options Options) Option
func WithPanicHandler(panicHandler func(interface{})) Option
func WithPreAlloc(preAlloc bool) Option
type Options
type Pool
func NewPool(size int, options ...Option) (*Pool, error)
func (p *Pool) Cap() int
func (p *Pool) Free() int
func (p *Pool) IsClosed() bool
func (p *Pool) Reboot()
func (p *Pool) Release()
func (p *Pool) Running() int
func (p *Pool) Submit(task func()) error
func (p *Pool) Tune(size int)
type PoolWithFunc
func NewPoolWithFunc(size int, pf func(interface{}), options ...Option) (*PoolWithFunc, error)
func (p *PoolWithFunc) Cap() int
func (p *PoolWithFunc) Free() int
func (p *PoolWithFunc) Invoke(args interface{}) error
func (p *PoolWithFunc) IsClosed() bool
func (p *PoolWithFunc) Reboot()
func (p *PoolWithFunc) Release()
func (p *PoolWithFunc) Running() int
func (p *PoolWithFunc) Tune(size int)const (//DefaultAntsPoolSize是默认goroutine池的默认容量。DefaultAntsPoolSize = math.MaxInt32//DefaultCleanIntervalTime是清理GoRoutine的间隔时间。DefaultCleanIntervalTime = time.Second
)const (//OPENED表示池已打开。OPENED = iota//CLOSED表示池已关闭。CLOSED
)var (//将负数设置为池容量时将返回ErrInvalidPoolSize,此错误将仅用于//通过设置负容量,不带func的池可以是无限的。ErrInvalidPoolSize = errors.New("invalid size for pool")//当调用程序不为池提供函数时,将返回ErrLackPoolFunc。ErrLackPoolFunc = errors.New("must provide function for pool")//将负数设置为清除goroutine的周期持续时间时,将返回ErrInvalidPoolExpiry。ErrInvalidPoolExpiry = errors.New("invalid expiry for pool")//将任务提交到关闭的池时,将返回ErrPoolClosed。ErrPoolClosed = errors.New("this pool has been closed")//当池已满且没有可用的工作线程时,将返回ErrPoolOverload。ErrPoolOverload = errors.New("too many goroutines blocked on submit or Nonblocking is set")//在预分配模式下尝试设置负容量时,将返回ErrInvalidPreAllocSize。ErrInvalidPreAllocSize = errors.New("can not set up a negative capacity under PreAlloc mode"))func Cap
func Cap() int
// Cap返回此默认池的容量。func Free
func Free() int
// 免费返回可用的goroutines以工作。func Reboot
func Reboot()
// 重新启动重新启动默认池。func Release
func Release()
// Release关闭默认池。func Running
func Running() int
// Running返回当前正在运行的goroutine数。func Submit
func Submit(task func()) error
// 提交将任务提交到池。// 类型
type Logger
type Logger interface {//Printf必须具有与log.Printf相同的语义。Printf(format string, args ...interface{})
}
// 记录器用于记录格式化消息。type Option
type Option func(opts *Options)
// 选项表示可选函数。func WithExpiryDuration
func WithExpiryDuration(expiryDuration time.Duration) Option
// WithExpiryDuration设置清理GoRoutine的间隔时间。func WithLogger
func WithLogger(logger Logger) Option
// WithLogger设置自定义记录器。func WithMaxBlockingTasks
func WithMaxBlockingTasks(maxBlockingTasks int) Option
// WithMaxBlockingTasks设置当GoRoutine达到池容量时被阻止的最大GoRoutine数。func WithNonblocking
func WithNonblocking(nonblocking bool) Option
// WithNonblocking表示当没有可用的工作线程时,池将返回nil。func WithOptions
func WithOptions(options Options) Option
// WithOptions接受整个选项配置。func WithPanicHandler
func WithPanicHandler(panicHandler func(interface{})) Option
// WithPanicHandler设置紧急处理程序。func WithPreAlloc
func WithPreAlloc(preAlloc bool) Option
// WithPreAlloc表示是否应为工作人员使用malloc。type Options
type Options struct {//过期时间是清道夫goroutine清理那些过期工人的时间,//清道夫会在每个“过期”期间扫描所有工人,并清理那些没有被清除的工人//用于超过“呼气时间”。ExpiryDuration time.Duration//PreAlloc指示初始化池时是否进行内存预分配。PreAlloc bool//pool.Submit上阻止goroutine的最大数目。//0(默认值)表示没有此类限制。MaxBlockingTasks int//当Nonblocking为true时,Pool.Submit将永远不会被阻止。//无法立即完成Pool.Submit时,将返回ErrPoolOverload。//当非阻塞为真时,MaxBlockingTasks不工作。Nonblocking bool//PanicHandler用于处理来自每个worker goroutine的恐慌。//如果为零,恐慌将再次从工人的狂欢中消失。PanicHandler func(interface{})//Logger是用于记录信息的自定义记录器,如果未设置,//使用日志包中的默认标准记录器。Logger Logger
}
// Options包含实例化ants池时将应用的所有选项。type Pool
type Pool struct {//包含已过滤或未报告的字段
}
// 池接受来自客户端的任务,它通过回收goroutine将goroutine的总数限制在给定的数量。func NewPool
func NewPool(size int, options ...Option) (*Pool, error)
// NewPool生成ants池的一个实例。func (*Pool) Cap
func (p *Pool) Cap() int
// Cap返回此池的容量。func (*Pool) Free
func (p *Pool) Free() int
// Free返回可用的goroutines以工作,-1表示此池是无限的。func (*Pool) IsClosed
func (p *Pool) IsClosed() bool
// IsClosed指示池是否已关闭。func (*Pool) Reboot
func (p *Pool) Reboot()
// 重新启动重新启动关闭的池。func (*Pool) Release
func (p *Pool) Release()
// Release关闭此池并释放工作队列。func (*Pool) Running
func (p *Pool) Running() int
// Running返回当前正在运行的goroutine数。func (*Pool) Submit
func (p *Pool) Submit(task func()) error
// 提交将任务提交到此池。func (*Pool) Tune
func (p *Pool) Tune(size int)
// Tune更改此池的容量,请注意,它对无限或预分配池无效。type PoolWithFunc
type PoolWithFunc struct {//包含已过滤或未报告的字段
}
// PoolWithFunc接受来自客户端的任务,它通过回收goroutine将goroutine的总数限制在给定数量。func NewPoolWithFunc
func NewPoolWithFunc(size int, pf func(interface{}), options ...Option) (*PoolWithFunc, error)
// NewPoolWithFunc使用特定函数生成ants池的实例。func (*PoolWithFunc) Cap
func (p *PoolWithFunc) Cap() int
// Cap返回此池的容量。func (*PoolWithFunc) Free
func (p *PoolWithFunc) Free() int
// Free返回一个可用的goroutines来工作,-1表示此池是无限的。func (*PoolWithFunc) Invoke
func (p *PoolWithFunc) Invoke(args interface{}) error
// Invoke将任务提交到池。func (*PoolWithFunc) IsClosed
func (p *PoolWithFunc) IsClosed() bool
// IsClosed指示池是否已关闭。func (*PoolWithFunc) Reboot
func (p *PoolWithFunc) Reboot()
// 重新启动重新启动关闭的池。func (*PoolWithFunc) Release
func (p *PoolWithFunc) Release()
// Release关闭此池并释放工作队列。func (*PoolWithFunc) Running
func (p *PoolWithFunc) Running() int
// Running返回当前正在运行的goroutine数。func (*PoolWithFunc) Tune
func (p *PoolWithFunc) Tune(size int)
// Tune更改此池的容量,请注意,它对无限或预分配池无效。

go第三方库文档 线程池ants相关推荐

  1. 查看本机中的python第三方库文档

    [转载] 原文链接:https://blog.csdn.net/weixin_43936250/article/details/105251049 本机系统为win10,在使用python编程的过程中 ...

  2. go第三方库文档 日志构建zap

    // go第三方库文档 日志构建zap // https://pkg.go.dev/go.uber.org/zap// 安装 // go get-u go.uber.org/zapQuick Star ...

  3. 基于 next.js + mdx 搭建组件库文档项目(二) -- mdx 控件封装实现组件的演示与 Props 列表

    说明 经过上阶段的配置虽然可以在项目中使用 mdx 语法 来创建页面了,但是我们的组件库有一些定制化的需求:交互式的组件演示.组件 Props 列表展示.这些功能如果可以通过封装来实现,会大大提升开发 ...

  4. 基于 next.js + mdx 搭建组件库文档项目(一) -- 开发环境搭建

    说明 之前使用过 Docz 来作为组件库文档搭建工具,它基于 gatsby , 提供了高度的定制化能力,但是截止 2021-06-22, Docz 停留在 v2.3.1(2020-04-05) 已经一 ...

  5. StoryBook 开发React组件库文档

    StoryBook 开发 React 组件库文档 说明 StoryBook 是一个开源的 UI 组件库构建工具,支持 React.Vue.Angular 等主流开发框架,使用 StoryBook 将获 ...

  6. 使用VitePress静态网站生成器创建组件库文档网站并部署到GitHub

    Vue3+TS+Vite开发组件库并发布到npm 网站在线预览: Vue Amazing UI | Amazing UI Components LibraryAmazing UI 组件库https:/ ...

  7. 并发库应用之三 线程池与定时器应用

    在TCP服务器编程模型的原理,每一个客户端连接用一个单独的线程为之服务,当与客户端的会话结束时,线程也就结束了,即每来一个客户端连接,服务器端就要创建一个新线程.如果访问服务器的客户端很多,那么服务器 ...

  8. 配置开发库文档的命名表

    做为项目组的人员比较关心一下几个问题: 按照CMMI3的标准,项目组要提交到SVN的文件清单(识别配置项). 每个文件的命名规范,比如:封面和修改记录中的版本命名规则.在SVN库中应该如何使用? 到底 ...

  9. 组件库系列三:编写组件库文档

    文章目录 vuepress介绍 创建文档工程 配置运行指令 vuepress浏览器自动更新 下载插件和依赖 npm/yarn link docs文件夹 .vuepress文件夹 可收缩代码块 效果展示 ...

最新文章

  1. D3D9学习笔记(四) 绘制
  2. 日发帖 发帖频率 发帖时段_先发帖
  3. 业界分享 | 美团到店综合知识图谱的构建与应用
  4. 醒醒吧,这世界上根本没有稳定的工作
  5. Flask-APScheduler使用教程
  6. 数据库的主键Id不是从1开始的
  7. arcmap新手教程_ArcGIS入门教程来袭,零基础的同学快看过来!
  8. 高品质的算法混响插件-Initial Audio AR1 Reverb v1.0.1 WiN-MAC
  9. 微服务网关——需求篇
  10. 在一个窗体的panel控件中显示其他窗体
  11. 系统架构设计笔记(19)—— 网络存储技术
  12. 水逆期自我救赎:MacBook pro进水
  13. 【转】专家:制造业将大批死亡 都怪马云
  14. MFC CString转ASCII字符串
  15. 百度霸屏什么意思?如何实现百度霸屏!
  16. Apache Camel源码研究之Rest
  17. 参加前端培训班哪个好
  18. 【动画】css实现旋转和平移效果
  19. VMware15.5创建Windows7教程
  20. 阿里微博双双IPO 最大受益者是新浪

热门文章

  1. 5月16日钢铁行业概览
  2. Windows 注册表相关API总结
  3. windows中Linux进入d盘,DOS命令进入D盘文件夹怎么操作
  4. Ubuntu 更改语言为中文
  5. 傻瓜式minio使用指南
  6. Mapper映射出错导致SpringBoot无法启动
  7. python中sample
  8. 【谷歌地图--集成准备】
  9. 浏览器前进与后退的秘密——栈 (栈的理解与实现)
  10. Windows-Terminal配置OhMyPosh来美化GitBash