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 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题