doushan15559 2018-07-25 13:43
浏览 59
已采纳

并发模式:具有可变结果数的工作程序

I want to create a worker pool in golang, to divide a big task in multiple jobs.

The problem is that the routines may produce multiple output as a result for the computation, so I cannot know in advance how many times I shall iterate over the results channel.

I know that I can use WaitGroup, but I was wondering if there is another pattern I can use, in order to let the main thread advanced on the computation and iterate over the results instead of waiting first every routine to be done.

Another solution I thought, which is not very elegant to me, is to create a Result struct or return an array of results. Since I can count the number of works, I know how many results arrays I'm gonna receive.

  • 写回答

1条回答 默认 最新

  • doufang3001 2018-07-25 14:04
    关注

    You can do something like this:

    go func() {
        wg.Wait()
        close(results)
    }()
    
    for res := range results {
        // Handle results
    }
    

    When all your workers finish processing, close the results channel. The process that's reading results will finish and then exit the loop.

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

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂