Goroutine 池是什么?
Goroutine 池是一个池子,里面有一些 Goroutine 。
这个池子有一个最大容量,其内部的 Goroutine 数量不能超过其最大容量。
可以将池子中的每个 Goroutine 看作是一个 worker ,用于执行任务。
更准确的说,Goroutine 池是一个架构。该架构由两部分组成:
一个池子,里面有一些 Goroutine 。
一个任务队列,里面放着给池子里的 Goroutine 执行的任务。
新来了一个任务,如果池子存满了 Goroutine ,而且它们都在工作,那么就将该任务放入任务队列,等待被处理;
如果池子没满,就新开一个 Goroutine 去处理该任务。
怎么实现 Goroutine 池?
Goroutine 池只是一个抽象的概念
Golang 没有封装好的线程池。
Goroutine 池只是一个概念,需要我们自己写代码时有意识地实现 Goroutine 池。
Goroutine 池的设计思路
启动服务的时候初始化一个 Goroutine Pool,这个协程池维护了 任务的管道 和 worker(也就是 Goroutine)。
外部将请求投递到 Goroutine Pool,Goroutine Pool 的操作是:判断当前运行的 worker 是否已经超过 Pool 的容量,如果超过就将请求放到任务管道中直到运行的 worker 将管道中的任务执行;如果没有超过就新开一个 worker 处理。
生产者消费者模型
在这个 投递 —> 等待 —> 执行 的过程中,我们很容易想到生产者消费者模型:
生产者 —(生产任务)–> 队列 —(消费任务)–> 消费者
实际上,用来执行任务的 goroutine 就是消费者,操作任务池的 goroutine 就是生产者, 而队列则可以使用 go 的 buffer channel,至此,任务池的建模到此结束。
一个实现 Goroutine 池的实例
题目:
- 计算一个数字的各个位数之和,例如数字123,结果为1+2+3=6。
- 随机生成数字进行计算。 ```go package main
import ( “fmt” “math/rand” )
type Job struct { Id int RandNum int }
type Result struct { job *Job sum int Id int }
func main() { jobChan := make(chan Job, 128) resultChan := make(chan Result, 128) createPool(64, jobChan, resultChan)
// 负责打印的协程go func(resultChan chan *Result) {for result := range resultChan {fmt.Printf("job id:%v randnum:%v result:%d work id:%v\n", result.job.Id, result.job.RandNum, result.sum, result.Id)}}(resultChan)var id intfor {id++r_num := rand.Int()job := &Job{Id: id,RandNum: r_num,}jobChan <- job}
}
func createPool(num int, jobChan chan Job, resultChan chan Result) { // 开启 num 个协程,做计算工作 for i := 0; i < num; i++ { go func(jobChan chan Job, resultChan chan Result, i int) { for job := range jobChan { r_num := job.RandNum var sum int for r_num != 0 { tmp := r_num % 10 sum += tmp r_num = r_num / 10 } r := &Result{ job: job, sum: sum, Id: i, } resultChan <- r } }(jobChan, resultChan, i) } }
job id:12718 randnum:4055691679846392811 result:94 work id:49
job id:12719 randnum:7367234545082916602 result:80 work id:50
job id:12720 randnum:2467998984845291017 result:103 work id:14
job id:12721 randnum:1915717660687400632 result:79 work id:27
job id:12722 randnum:1999076364581566121 result:89 work id:40
job id:12723 randnum:6896587575922113626 result:98 work id:54
job id:12724 randnum:7027466925438669614 result:95 work id:28
```

如上图,本程序由两个协程、一个协程池、两个管道构成。
job 协程不断产生任务,然后放入 jobchan 任务队列;协程池中有64个协程,不断地从任务队列 jobchan 中取任务来执行,将结果放入 resultchan 任务队列;printf 协程从 resultchan 任务队列中取出结果来进行打印。
其中,我们可以看到两对生产者消费者:job 协程和协程池是一对生产者消费者,协程池和printf 协程也是一对生产者消费者。
说明:
在这个例子中,两个管道和协程池可以理解为 “Goroutine 池”。
它的作用是一直在用有限的 Goroutine 数量进行一项无限的工作。
试想,如果没有这两个管道和协程池:
job 协程一直在产生任务,来一个任务就要创建一个协程计算它…那将是无数个协程…
总结
worker pool(goroutine池):
- 本质上是生产者消费者模型
- 可以有效控制 goroutine 数量,防止暴涨
参考连接
https://blog.csdn.net/weixin_44211968/article/details/123048160
