duanche8554 2014-03-04 19:54
浏览 24
已采纳

GO-for循环中的子例程行为

I'm having some doubts on my understanding of the behaviour of a go subroutine in a for loop.

From what I understand, when we have a for loop:

for key := range Map {
   go subroutine(Map[key])
}

Where Map has, let's say 3 (key,Value) pairs.

So my understanding is that the subroutine() function will run concurrently using all the Map[Key] values ie subroutine(Map[key1]),subroutine(Map[key2]) and subroutine(Map[key3]) will all run concurrently ?

Is my understanding of concurrent subroutines in a for loop correct?

Thanks!

  • 写回答

1条回答 默认 最新

  • douzha6055 2014-03-06 20:14
    关注

    Yes. Please remember that you will still need the main goroutine alive for these to finish before the program ends. You can use something like sync.WaitGroup:

    wg := new(sync.WaitGroup)
    for key := range Map {
      wg.Add(1)
      go func() {
        subroutine(Map[key])
        wg.Done()
      }
    }
    wg.Wait()
    

    Or if you have something like a server loop going on in the main routine you may not need that at all since your program won't finish until a relevant signal is externally sent to it.

    Hope that helps.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?