dqan70724 2018-01-08 04:12
浏览 16
已采纳

如何检查工人通道是否打开?

Here is what I'm doing: a few workers and queue with job for them.

I have a simple worker:

func worker(jobs <-chan int, wg *sync.WaitGroup) {
    for work := range jobs {
        perform(work)
    }
    wg.Done()
}

Start them:

    jobs := make(chan int)
    var wg sync.WaitGroup

    for w := 1; w <= parallel; w++ {
        wg.Add(1)
        go worker(jobs, &wg)
    }

Also I have a queue, and here goes problem, how to check if there is available worker and write only then?

func queue(jobs chan int, stop chan bool) {
    for {
            select {
            case jobs<-?: // How to check what worker is available?
                work := receiveWork()
                jobs <- work
                continue
            case <-stop:
                return
            }
        }
    }
}

Start queue:

stop := make(chan bool)
go queue(jobs, stop)

Note what receiveWork() should be called only if there is an available worker.

  • 写回答

1条回答 默认 最新

  • duanruinong0619 2018-01-08 06:22
    关注

    One option to use two channels, one for ready and one for the actual work:

    func worker(ready chan struct{}, work chan int, wg *sync.WaitGroup) {
        for range ready {
            w, ok := <-work
            if !ok {
                break
            }
            perform(w)
        }
        wg.Done()
    }
    
    func queue(ready chan struct{}, work chan int, stop chan struct{}) {
        defer close(ready)
        defer close(work)
        for {
            select {
            case ready <- struct{}{}:
                work <- receiveWork()
            case <-stop:
                return
            }
        }
    }
    

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器