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!

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top