GO如何实现协程池管理 GO实现协程池管理代码方法

作者:袖梨 2022-06-25

GO如何实现协程池管理?本篇文章小编给大家分享一下GO实现协程池管理代码方法,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

使用channel实现协程池

通过 Channel 实现 Goroutine Pool,缺点是会造成协程的频繁开辟和注销,但好在简单灵活通用。

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"sync"
)

// Pool goroutine Pool
type Pool struct {
	queue chan int
	wg    *sync.WaitGroup
}

// New 新建一个协程池
func New(size int) *Pool {
	if size  delta; i-- {
		

消费者模式实现协程池

频繁对协程开辟与剔除,如果对性能有着很高的要求,建议优化成固定数目的协程取 channel 里面取数据进行消费,这样可以避免协程的创建与注销。

package main

import (
	"fmt"
	"strconv"
	"sync"
)

// 任务对象
type task struct {
	Production
	Consumer
}

// 设置消费者数目,也就是work pool大小
func (t *task) setConsumerPoolSize(poolSize int) {
	t.Production.Jobs = make(chan *Job, poolSize*10)
	t.Consumer.WorkPoolNum = poolSize
}

// 任务数据对象
type Job struct {
	Data string
}

func NewTask(handler func(jobs chan *Job) (b bool)) (t *task) {
	t = &task{
		Production: Production{Jobs: make(chan *Job, 100)},
		Consumer:   Consumer{WorkPoolNum: 10, Handler: handler},
	}
	return
}

type Production struct {
	Jobs chan *Job
}

func (c Production) AddData(data *Job) {
	c.Jobs 

相关文章

精彩推荐