美文网首页
看别个的协程池自己练了下

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

作者: phu | 来源:发表于2018-10-29 10:09 被阅读0次

    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()
    }

    参考:https://www.jianshu.com/p/508f5d3b2f59

    相关文章

      网友评论

          本文标题:看别个的协程池自己练了下

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