近段时间,在用go的时候找了许久没有发现go协成池之类的东西,然后自己脑子一热,手撸的一个协成池,希望这个东西可以帮助到,也在go语言中苦苦寻求go协成池的伙伴,有什么想法可以留言到下面
go
func TestGoPoll(t *testing.T) {
task := NewTask(func() error {
fmt.Println(time.Now())
return nil
})
taskCount := 0
ticker := time.NewTicker(2 * time.Second)
p := NewWorkPool(3)
go func(c *time.Ticker) {
for {
p.TaskQueue <- task
<-c.C
taskCount++
if taskCount == 5 {
p.close()
break
}
}
return
}(ticker)
p.run()
}
type Task struct {
f func() error
}
func NewTask(f func() error) *Task {
return &Task{f: f}
}
type WorkPool struct {
TaskQueue chan *Task
workNum int
shop chan struct{}
}
func NewWorkPool(cap int) *WorkPool {
if cap <= 0 {
cap = 10
}
return &WorkPool{
TaskQueue: make(chan *Task),
workNum: cap,
shop: make(chan struct{}),
}
}
func (t *Task) Execute() error {
return t.f()
}
func (p *WorkPool) worker(workerId int) {
for task := range p.TaskQueue {
err := task.Execute()
if err != nil {
fmt.Println(err)
continue
}
fmt.Printf("worker %d finished\n", workerId)
}
}
func (p *WorkPool) run() {
for i := 0; i < p.workNum; i++ {
go p.worker(i)
}
<-p.shop
}
func (p *WorkPool) close() {
p.shop <- struct{}{}
}