golang简易工作池

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简易工作池)