分享
golang40行代码实现通用协程池
xialeistudio · · 1388 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
代码仓库
golang的协程管理
golang协程机制很方便的解决了并发编程的问题,但是协程并不是没有开销的,所以也需要适当限制一下数量。
不使用协程池的代码(示例代码使用chan实现,代码略啰嗦)
func (p *converter) upload(bytes [][]byte) ([]string, error) {
ch := make(chan struct{}, 4)
wg := &sync.WaitGroup{}
wg.Add(len(bytes))
ret := make([]string, len(bytes))
// 上传
for index, item := range bytes {
ch <- struct{}{}
go func(index int, imageData []byte) {
defer func() {
wg.Done()
<-ch
}()
link, err := qiniu.UploadBinary(imageData, fmt.Sprintf("%d.png", time.Now().UnixNano()))
if err != nil {
log.Println("上传图片失败", err.Error())
return
}
ret[index] = link
}(index, item)
}
wg.Wait()
return ret, nil
}
需要实现的需求有两个:
- 限制最大协程数,本例为4
- 等待所有协程完成,本例为
bytes切片长度
使用协程池的代码
func (p *converter) upload(bytes [][]byte) ([]string, error) {
ret := make([]string, len(bytes))
pool := goroutine_pool.New(4, len(bytes))
for index, item := range bytes {
index := index
item := item
pool.Submit(func() {
link, err := qiniu.UploadBinary(item, fmt.Sprintf("%d.png", time.Now().UnixNano()))
if err != nil {
log.Println("上传图片失败", err.Error())
return
}
ret[index] = link
})
}
pool.Wait()
return ret, nil
}
可以看到最大的区别是只需要关注业务逻辑即可,并发控制和等待都已经被协程池接管
写在最后
希望本文能减轻你控制协程的负担
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信1388 次点击
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
代码仓库
golang的协程管理
golang协程机制很方便的解决了并发编程的问题,但是协程并不是没有开销的,所以也需要适当限制一下数量。
不使用协程池的代码(示例代码使用chan实现,代码略啰嗦)
func (p *converter) upload(bytes [][]byte) ([]string, error) {
ch := make(chan struct{}, 4)
wg := &sync.WaitGroup{}
wg.Add(len(bytes))
ret := make([]string, len(bytes))
// 上传
for index, item := range bytes {
ch <- struct{}{}
go func(index int, imageData []byte) {
defer func() {
wg.Done()
<-ch
}()
link, err := qiniu.UploadBinary(imageData, fmt.Sprintf("%d.png", time.Now().UnixNano()))
if err != nil {
log.Println("上传图片失败", err.Error())
return
}
ret[index] = link
}(index, item)
}
wg.Wait()
return ret, nil
}
需要实现的需求有两个:
- 限制最大协程数,本例为4
- 等待所有协程完成,本例为
bytes切片长度
使用协程池的代码
func (p *converter) upload(bytes [][]byte) ([]string, error) {
ret := make([]string, len(bytes))
pool := goroutine_pool.New(4, len(bytes))
for index, item := range bytes {
index := index
item := item
pool.Submit(func() {
link, err := qiniu.UploadBinary(item, fmt.Sprintf("%d.png", time.Now().UnixNano()))
if err != nil {
log.Println("上传图片失败", err.Error())
return
}
ret[index] = link
})
}
pool.Wait()
return ret, nil
}
可以看到最大的区别是只需要关注业务逻辑即可,并发控制和等待都已经被协程池接管
写在最后
希望本文能减轻你控制协程的负担