看别个的协程池自己练了下

package main

import "fmt"

type Task struct {
doSth func() error
}

func NewTask(taskFunc func() error) (task *Task){
task=&Task{
doSth:taskFunc,
}
return
}
func (t *Task)Execute() {
t.doSth()
}

//
type Pool struct {
entryChannel chan *Task
workerNum int
jobsChannel chan *Task
}

func NewPool(cap int) (pool *Pool ){
pool=&Pool{
entryChannel:make(chan *Task),
workerNum:cap,
jobsChannel:make(chan *Task),
}
return
}
func (p *Pool)Worker(workerId int) {
for task:=range p.jobsChannel {
task.Execute()
}

}
func (p *Pool)Run() {

for i:=0;i<p.workerNum;i++ {
    go p.Worker(i)
}
for task:=range p.entryChannel {
    p.jobsChannel<-task
}
close(p.jobsChannel)
close(p.entryChannel)

}
func main() {
t:=NewTask(func() error {
fmt.Println("123")
return nil
})
t2:=NewTask(func() error {
fmt.Println("456")
return nil
})
pool:=NewPool(3)
go func() {
for {
pool.entryChannel<-t
pool.entryChannel<-t2

}

}()
pool.Run()
}

参考://www.greatytc.com/p/508f5d3b2f59

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容