I am interested to calculate correlations in parallel in Go. The main problem I have is that all the Go processes seems to execute exactly the same calculation. I reproduced here the problem with a very simple example. I obtain :
4 + 50 = 54 4 + 50 = 54 4 + 50 = 54 instead of :
1 + 20 = 21 2 + 30 = 32 3 + 40 = 43 If I move up "wg.Wait()" I obtain the good result but no parallelism :( Thank's in advance for your comments !
package main import ( "fmt" "runtime" "sync" ) func process_array(x, y int) int { r := x + y return r } func main() { a1 := []int{0, 1, 2, 3, 4} a2 := []int{10, 20, 30, 40, 50} runtime.GOMAXPROCS(8) var wg sync.WaitGroup for i := 1; i < 4 ; i++ { wg.Add(1) go func() { defer wg.Done() x :=process_array(a1[i],a2[i]) fmt.Println(a1[i],"+", a2[i],"=", x) }() //wg.Wait() give the good result //but it is not parallel processing // 1 + 20 = 21 // 2 + 30 = 32 // 3 + 40 = 43 } wg.Wait() // give a repetition of the same result : // 4 + 50 = 54 // 4 + 50 = 54 // 4 + 50 = 54 }