dte29947 2017-08-12 14:30
浏览 94
已采纳

工作线程池

In the example provided at http://marcio.io/2015/07/handling-1-million-requests-per-minute-with-golang/ which has been cited in a lot of places.

func (d *Dispatcher) dispatch() {
for {
    select {
    case job := <-JobQueue:
        // a job request has been received
        go func(job Job) {
            // try to obtain a worker job channel that is available.
            // this will block until a worker is idle
            jobChannel := <-d.WorkerPool

            // dispatch the job to the worker job channel
            jobChannel <- job
         }(job)
    }
}
}

Wouldn't the worker pool (chan chan job) get depleted after MaxWorker number of jobs have been serviced by the dispatch? Since <-d.WorkerPool is pulling from the channel and job channels are not being replenished after the first type dispatcher.Run() is invoked the first time? Or am I missing/misreading something ? How is the WorkerPool getting replenished with available job channels ?

go func(job Job) {
            // try to obtain a worker job channel that is available.
            // this will block until a worker is idle
            jobChannel := <-d.WorkerPool

            // dispatch the job to the worker job channel
            jobChannel <- job
        }(job)
  • 写回答

1条回答 默认 最新

  • douyi4544 2017-08-12 14:43
    关注

    if you read the code of worker carefully, you will notice

    w.WorkerPool <- w.JobChannel
    

    each time a loop begin, the channel of worker itself has been put back

    I copy the whole function below:

    func (w Worker) Start() {
        go func() {
            for {
                // register the current worker into the worker queue.
                w.WorkerPool <- w.JobChannel
    
                select {
                case job := <-w.JobChannel:
                    // we have received a work request.
                    if err := job.Payload.UploadToS3(); err != nil {
                        log.Errorf("Error uploading to S3: %s", err.Error())
                    }
    
                case <-w.quit:
                    // we have received a signal to stop
                    return
                }
            }
        }()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘