joe
joe

Reputation: 335

Incorrect values inside goroutines when looping

I have read through CommonMistakes as well as run my code through the -race flag, but I can't seem to pinpoint what is wrong here:

package main

import (
    "fmt"
)

func main() {
    i := 1
    totalHashFields := 6
    for i <= totalHashFields {
        Combinations(totalHashFields, i, func(c []int) {
            fmt.Println("Outside goroutine:", c)
            go func(c []int) {
                fmt.Println("Inside goroutine:", c)
            }(c)
        })
        i++
    }
}

func Combinations(n, m int, emit func([]int)) {
    s := make([]int, m)
    last := m - 1
    var rc func(int, int)
    rc = func(i, next int) {
        for j := next; j < n; j++ {
            s[i] = j
            if i == last {
                emit(s)
            } else {
                rc(i+1, j+1)
            }
        }
        return
    }
    rc(0, 0)
}

(The Combinations function is a combinations algo for those interested)

Here is some of the output from fmt.Println:

Outside goroutine: [0 1 4]
Inside goroutine: [5 5 5]
Outside goroutine: [0 1 2 3 4 5]
Inside goroutine: [5 5 5 5 5 5]

Basically, even though I'm passing c as a parameter to my anonymous go function, the value is consistently different to the value outside of this scope. In the output above, I expected the 2 "Inside" values to also be [0 1 4] and [0 1 2 3 4 5], respectfully.

Upvotes: 4

Views: 434

Answers (1)

Volker
Volker

Reputation: 42403

The problem is that you goroutines all work on distinc int slices but these share a common backing array: After completing Combinations the slice s will be full of 5s. Your c in main shares the underlying backing array with s.

But your goroutines do not start executing until Combinations is done so once they do start, the will see the final value of s which is just 5s.

Here it does not help to pass in the slice like you did as this makes a proper copy of c but not of the backing array.

Try

Combinations(totalHashFields, i, func(c []int) {
    fmt.Println("Outside goroutine:", c)
    cpy := make([]int, len(c))
    copy(cpy, c)
    go func(c []int) {
        fmt.Println("Inside goroutine:", c)
    }(cpy)
})

to make a "deep copy" of c.

Upvotes: 2

Related Questions