Golang(九)简单 Goroutine 池实现
0. 前言
- 最近使用 Golang 写一个并发执行的测试脚本
- 之前习惯使用 Java,习惯性想先建一个线程池。然后意识到 Golang 没有封装好的线程池
- 结合之前学习的 Goroutine 原理和 Golang 大道至简的设计思想,可能 Goroutine 的开销和切换代价比较低,不需要对并发数有过多限制
- 但是 Goroutine 启动数量过多的话总感觉不太好,于是利用锁和通道实现了简单的线程池做并发控制,欢迎大家点评
- 源码地址:https://github.com/wangao1236/GoPool
1. 相关接口
- 接口仿照 Java 的 ExecutorService 和 Runnable 接口定义:
// Task represents an in-process Goroutine task.
type Task interface {
// Run method corresponds to Run method of Java's Runnable interface.
Run()
} // Executor defines the actions associated with the Goroutine pool.
type Executor interface {
// Execute method corresponds to Execute method of Java's ExecutorService interface.
Execute(task Task)
// Wait waits for all the tasks to complete.
Wait()
// Done returns a channel which is closed if all the tasks completed.
Done() chan struct{}
}
- 接口调用:
func TestNewExecutor(t *testing.T) {
t.Log(t.Name())
ex := NewExecutor()
for _, domain := range domains {
ex.Execute(&TestTask{
fmt.Sprintf("ping %s -c 10", domain),
})
}
ex.Wait()
}
- 首先定义一个 Executor,然后通过 Execute 传入 Task 对象,调用 Wait 方法等待所有任务结束
2. 具体实现
- 主要利用 sync.Mutex 和 []channel struct{} 维护一个等待执行的任务队列
- 任务传入时,等待一个 startCh 通道信号
- 对于符合执行条件(未设定并发数或者当前执行任务小于并发数时)关闭 startCh 信号,解除阻塞
- 任务执行完毕后,关闭 stopCh 信号,允许等待队列里的任务继续执行
- 对于所有任务执行完毕(正在执行数和等待执行数均为 0),关闭 done 信号,解除整个 Executor 的阻塞,表示所有任务执行完毕
- 部分代码如下:
package pkg import (
"sync"
) // Task represents an in-process Goroutine task.
type Task interface {
// Run method corresponds to Run method of Java's Runnable interface.
Run()
} // Executor defines the actions associated with the Goroutine pool.
type Executor interface {
// Execute method corresponds to Execute method of Java's ExecutorService interface.
Execute(task Task)
// Wait waits for all the tasks to complete.
Wait()
// Done returns a channel which is closed if all the tasks completed.
Done() chan struct{}
} type executor struct {
lock sync.Mutex
waitingTasks []chan struct{}
activeTasks int64
concurrencyLimit int64
done chan struct{}
} func (ex *executor) Execute(task Task) {
ex.start(task)
} func (ex *executor) Wait() {
<-ex.done
} func (ex *executor) Done() chan struct{} {
return ex.done
} func (ex *executor) start(task Task) {
startCh := make(chan struct{})
stopCh := make(chan struct{}) go startTask(startCh, stopCh, task)
ex.enqueue(startCh)
go ex.waitDone(stopCh) } // NewExecutor returns a new Executor.
func NewExecutor(concurrencyLimit int64) Executor {
ex := &executor{
waitingTasks: make([]chan struct{}, ),
activeTasks: ,
concurrencyLimit: concurrencyLimit,
done: make(chan struct{}),
}
return ex
} func startTask(startCh, stopCh chan struct{}, task Task) {
defer close(stopCh) <-startCh
task.Run()
} func (ex *executor) enqueue(startCh chan struct{}) {
ex.lock.Lock()
defer ex.lock.Unlock() if ex.concurrencyLimit == || ex.activeTasks < ex.concurrencyLimit {
close(startCh)
ex.activeTasks++
} else {
ex.waitingTasks = append(ex.waitingTasks, startCh)
}
} func (ex *executor) waitDone(stopCh chan struct{}) {
<-stopCh ex.lock.Lock()
defer ex.lock.Unlock() if len(ex.waitingTasks) == {
ex.activeTasks--
if ex.activeTasks == {
close(ex.done)
}
} else {
close(ex.waitingTasks[])
ex.waitingTasks = ex.waitingTasks[:]
}
}
- 通过 Executor 传入的任务首先开始执行 start 方法
- start 方法里定义了该任务的 startCh 和 stopCh 信号
- 各启动一个 Goroutine 等待任务开始和任务结束
- 同时把表示任务的 startCh 加入等待队列中表示,队列需要靠 sync.Mutex 保护
- 当一个任务结束时,解除 waitDone 方法的阻塞,启动队首的任务,解除 startTask 里的阻塞
- 所有任务结束后,解除 Wait 方法里的阻塞
- 完整代码参见上述链接
Golang(九)简单 Goroutine 池实现的更多相关文章
- golang中goroutine池的使用
1. 概念本质上是生产者.消费者模型可以有效的控制goroutine数量,防止暴涨案例:生成一个随机数,计算该随机数每一个数字相加的和,例如:123:1+2+3=6主协程负责生产数据发送到待处理通道中 ...
- Golang之chan/goroutine(转)
原文地址:http://tchen.me/posts/2014-01-27-golang-chatroom.html?utm_source=tuicool&utm_medium=referra ...
- gf框架之grpool - 高性能的goroutine池
Go语言中的goroutine虽然相对于系统线程来说比较轻量级,但是在高并发量下的goroutine频繁创建和销毁对于性能损耗以及GC来说压力也不小.充分将goroutine复用,减少goroutin ...
- 菜鸟nginx源代码剖析数据结构篇(九) 内存池ngx_pool_t
菜鸟nginx源代码剖析数据结构篇(九) 内存池ngx_pool_t Author:Echo Chen(陈斌) Email:chenb19870707@gmail.com Blog:Blog.csdn ...
- 菜鸟nginx源码剖析数据结构篇(九) 内存池ngx_pool_t[转]
菜鸟nginx源码剖析数据结构篇(九) 内存池ngx_pool_t Author:Echo Chen(陈斌) Email:chenb19870707@gmail.com Blog:Blog.csdn. ...
- [Golang] 一个简易代理池
晚上写了一个代理池,就是在一个代理网站上爬取代理ip和端口以及测试是否可用.接下来可能考虑扩展成一个比较大的 golang实现的代理池. 简易版代码: package main import ( &q ...
- Linux多线程实践(9) --简单线程池的设计与实现
线程池的技术背景 在面向对象编程中,创建和销毁对象是很费时间的,因为创建一个对象要获取内存资源或者其它更多资源.在Java中更是如此,虚拟机将试图跟踪每一个对象,以便能够在对象销毁后进行垃圾回收.所以 ...
- Linux下简单线程池的实现
大多数的网络服务器,包括Web服务器都具有一个特点,就是单位时间内必须处理数目巨大的连接请求,但是处理时间却是比较短的.在传统的多线程服务器模型中是这样实现的:一旦有个服务请求到达,就创建一个新的服务 ...
- Golang设计模式—简单工厂模式(Simple Factory Pattern)
Golang设计模式--简单工厂模式 背景 假设我们在做一款小型翻译软件,软件可以将德语.英语.日语都翻译成目标中文,并显示在前端. 思路 我们会有三个具体的语言翻译结构体,或许以后还有更多,但现在分 ...
随机推荐
- 将VMWare中的虚拟机时间设定在一个固定值
1.关闭虚拟机 2.用记事本打开虚拟机的.vmx文件 在末尾添加添加: tools.syncTime = "FALSE" time.synchronize.continue = ...
- C#面试基础知识点:值类型和引用类型(1)(填坑文)
目录 前言 C#值类型和引用类型 基类(共同点) 值类型继承基类(不同点) 应用类型继承 技术经理的问题 值类型与引用类型都可以用Equals来比较吗? 如何将一个数组a的值赋予数组b然后对b做修改而 ...
- JS读取xml
xml文件 <?xml version="1.0" encoding="utf-8"?> <root> <data id=&quo ...
- windows下编写dll
dll的优点 简单的说,dll有以下几个优点: 1) 节省内存.同一个软件模块,若是以源代码的形式重用,则会被编译到不同的可执行程序中,同时运行这些exe时这些模块的二进制码会被重复加载到内存中.如果 ...
- JavaScript 字符串(String) 大全
JavaScript字符串存储一系列字符,如“John Doe”.字符串可以是双引号或单引号内的任何文本: <!DOCTYPE html> <html> <meta ch ...
- SVG撑满页面
当viewBox属性固定,默认修改svg标签的宽高,svg都会按比例缩放 我们现在不想按比例缩放,需要svg撑满整个画面 这里只需为svg标签添加一个关键属性:preserveAspectRatio ...
- IntelliJ IDEA 中使用 Lambok (注解无效问题的解决)
一,概述 Lambok可以说一个能很大提高开发效率的插件,只要在使用注解的方式就能实现很多常用的功能.如常用的@Data能在编译阶段自动生成toString方法,getter方法setter方法等. ...
- mysql Waiting for table flush
应用突然被hang住了,tomcat日志报错,所有涉及到数据库的操作都报错,卡死. show processlist 查看到大量的:Waiting for table flush 应该是 进行了 dd ...
- 五、select的5种子句
1.Where 条件查询 比较运算符: 运算符 说明 > < = >= <= !=或<> In 在某集合内 between 在某范围内 In ...
- Qt 之 qwt 和 qwtpolar 的编译配置
1 Qwt Qwt 全称为 Qt Widgets for Technical Applications,用于专业技术领域的可视化显示,如下所示: 左图为二阶系统的频率响应:中图为德国小城 Fried ...