普通网友 2014-02-14 20:50
浏览 47
已采纳

我们应该做嵌套goroutines吗?

I'm trying to build a parser for a huge amount of file, and I can't find ressource about what I may call "nested goroutines" (maybe this is not the right name ?).

Given a lot of files, each of them having a lot of lines. Should I do:

for file in folder:
    go do1

def do1:
    for line in file:
        go do2

def do2:
    do_something

Or should I use only "one level" of goroutines, and do the following:

for file in folder:
    for line in file:
        go do_something

My question target primarily performance issues.

Thanks for reaching that sentence !

  • 写回答

2条回答 默认 最新

  • dongmi1941 2014-02-14 21:41
    关注

    If you go through with the architecture you've specified, you have a good chance of running out of CPU/Mem/etc because you're going to be creating an arbitrary amount of workers. I suggest, instead go with an architecture that allows you to throttle via channels. For example:

    In your main process feed the files into a channel:

    for _, file := range folder {
      fileChan <- file
    }
    

    then in another goroutine break the files into lines and feed those into a channel:

    for {
      select{
      case file := <-fileChan
        for _, line := range file {
          lineChan <- line
        }
      }
    }
    

    then in a 3rd goroutine pop out the lines and do what you will with them:

    for {
      select{
      case line := <-lineChan:
        // process the line
      }
    }
    

    The main advantage to this is that you can create as many or as few go routines as your system can handle and pass them all the same channels and whichever go routine gets to the channel first will just handle it, so you're able to throttle the amount of resources you're using.

    Here is a working example: http://play.golang.org/p/-Qjd0sTtyP

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程