iLoveWagons
iLoveWagons

Reputation: 1141

GO - subroutine behaviour in a for loop

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!

Upvotes: 0

Views: 1957

Answers (1)

Marcin Wyszynski
Marcin Wyszynski

Reputation: 2258

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.

Upvotes: 2

Related Questions