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 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)