I have this following program where I am trying to store some final results based on each go-routine and the trick I am using to not have race condition is by designating a particular array index for each go-routine.
func TestHHH(t *testing.T) {
arr := []int{1, 2, 3, 4, 5}
result := make([]int, len(arr))
wg := sync.WaitGroup{}
for i, v := range arr {
index := i
val := v
go func() {
wg.Add(1)
defer wg.Done()
result[index] = val
}()
}
wg.Wait()
fmt.Println(result)
}
I understand I can use mutexes or channels to fix the race condition, but I am just wondering why the above code has a race condition. I wanted the go-routines to be faster instead of waiting for mutex locks or waiting for channel operations.
Isn’t it each go-routine pointing to different indexes that are mutually exclusive?