如何使用golang快速实现协程池
1.下面将通过一个案例来学习协程池的调度和运作,废话不多说,直接开撸。
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
t := NewTask(func() error{
fmt.Println(time.Now())
return nil
})
p := NewPool(4)
go func() {
for{
p.AddTask(t)
time.Sleep(time.Second)
}
}()
p.RunWorker()
select {
}
}
type Task struct {
F func()error
}
func NewTask(f func()error)*Task {
return &Task{
F:f,
}
}
type Pool struct {
MaxSize int //协程数量大小
Worker []chan *Task //任务管道
}
func NewPool(maxSize int)*Pool {
return &Pool{
MaxSize:maxSize,
Worker:make([]chan *Task,maxSize),
}
}
func (this *Pool)RunWorker() {
for i:=0;i<this.MaxSize;i++{
this.Worker[i] = make(chan *Task,1024)
go this.Start(i,this.Worker[i])
}
}
func (this *Pool)Start(index int,tasks chan *Task) {
for task:= range tasks{
fmt.Println("this is workerID:",index)
task.F()
}
}
func (this *Pool)AddTask(t *Task) {
index := rand.Intn(this.MaxSize)
this.Worker[index] <- t
}