美文网首页
golang简易工作池

golang简易工作池

作者: funcx | 来源:发表于2018-11-29 14:28 被阅读12次
    type Pool struct {
        workerNum int
        jobQue    chan func() error
        wg        sync.WaitGroup
    }
    
    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 {
            xlog.Info.Println("workId:", workId)
            f()
        }
        p.wg.Done()
    }
    
    func (p *Pool) Run() {
        for i := 0; i < p.workerNum; i++ {
            go p.work(i)
            p.wg.Add(1)
        }
        p.wg.Wait()
    }
    
    func (p *Pool) colse() {
        close(p.jobQue)
    }
    
    func main() {
        pool := NewPool(5)
        go func() {
            for i := 0; i < 5; i++ {
                pool.AddTask(func() error {
                    log.Println(time.Now())
                    return nil
                })
                time.Sleep(time.Second)
            }
            pool.colse()
        }()
        pool.Run()
    }
    

    相关文章

      网友评论

          本文标题:golang简易工作池

          本文链接:https://www.haomeiwen.com/subject/pbqfcqtx.html