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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。