线程池的构成:有工作者,有待上机器运作的商品,给每个工作者分配自己要负责的商品,保证他们正常运转,一件商品完成之后,要能把这个信息传递出去,然后分配下一个商品
所以结构体要有
工作者:(工作者编号)
工作的地方:工作者(work),传送带(管道chan)要处理的商品(taskQueue),保证所以商品都完成的机制(sycn.Waitgroup)
package main
import (
"fmt"
"sync"
)
type Worker struct {
Id int
}
type Pool struct {
Worker []Worker
TaskQueue chan func()
wg sync.WaitGroup
}
func main() {
//创建线程池
newPool := NewPool(3, 10)
//启动工作人员
for i := 0; i < len(newPool.Worker); i++ {
newPool.Worker[i].Start(newPool)
}
//工作人员准备好,之后提交任务到线程池,让工作人员准备工作
for i := 0; i < 8; i++ {
id := i
newPool.Submit(func() {
fmt.Printf("Task %d is runing by worker %d\n", id, id%5)
})
}
//关闭线程池,等待所有任务完成
newPool.Shutdown()
}
func NewPool(worker int, taskQueue int) *Pool {
myPool := &Pool{
TaskQueue: make(chan func(), taskQueue),
}
myPool.Worker = make([]Worker, worker)
for i := 0; i < taskQueue; i++ {
myPool.Worker[i] = Worker{Id: i}
}
}
func (worker Worker) Start(pool *Pool) {
go func() {
for task := range pool.TaskQueue {
task()
pool.wg.Done()
}
}()
}
func (pool Pool) Submit(task func()) {
pool.wg.Add(1)
pool.TaskQueue <- task
}
func (pool Pool) Shutdown() {
close(pool.TaskQueue)
pool.wg.Wait()
}