How to run in parallel this code

Hi all,
I have the following code:

num := 100;
for i1 := 0; i1 < num; i1++ {
	for i2 := 0; i2 < num; i2++ {
		for i3 := 0; i3 < num; i3++ {
			for i4 := 0; i4 < num; i4++ {
				// Body code
			}
		}
	}
}

How to run this code in parallel mode?
Any idea to help?
Thank you,

Is the body code referring to the loop variables i1, … i4? Then you could start a Goroutine:

// Body code
go func(a int, b int, c int, d int) {
  // do something
} (i1, i2, i3, i4) // We have to capture the values here!

But depending on how large num is and what the body code does, this may not be the best idea. You will start num^4 goroutines and if each uses some limited resource, you may overload this resource.

1 Like

Thank you,

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.