type Pool struct {
workerNum int
jobQue chan func() error
}
func NewPool(wn int) *Pool {
return &Pool{workerNum: wn, jobQue: make(chan func() error)}
}
func (p *Pool) AddTask(f func() error) {
p.jobQue <- f
}
func (p *Pool) work(workId int) {
for f := range p.jobQue {
f()
}
}
func (p *Pool) Run() {
for i := 0; i < p.workerNum; i++ {
go p.work(i)
}
select {}
}
func main1() {
pool := NewPool(3)
f := func() error {
fmt.Println(time.Now())
return nil
}
go func() {
for {
pool.AddTask(f)
}
}()
pool.Run()
}
有疑问加站长微信联系(非本文作者)