在循环时,goroutine 内部的值不正确。

huangapple go评论85阅读模式
英文:

Incorrect values inside goroutines when looping

问题

我已经阅读了CommonMistakes并且通过-race标志运行了我的代码,但是我似乎无法确定问题出在哪里:

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)
}

(Combinations函数是一个组合算法,对于那些感兴趣的人)

这是一些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]

基本上,尽管我将c作为参数传递给我的匿名go函数,但该值始终与该作用域外的值不同。在上面的输出中,我期望的两个"Inside"值也分别是[0 1 4]和[0 1 2 3 4 5]。

英文:

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 (
	&quot;fmt&quot;
)

func main() {
	i := 1
	totalHashFields := 6
	for i &lt;= totalHashFields {
		Combinations(totalHashFields, i, func(c []int) {
			fmt.Println(&quot;Outside goroutine:&quot;, c)
			go func(c []int) {
				fmt.Println(&quot;Inside goroutine:&quot;, 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 &lt; 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.

答案1

得分: 2

问题在于你的 goroutine 都在不同的 int 切片上工作,但它们共享一个公共的底层数组:在完成 Combinations 后,切片 s 将被填满 5。你在主函数中的 cs 共享相同的底层数组。

但是你的 goroutine 在 Combinations 完成之前不会开始执行,所以一旦它们开始执行,它们将看到 s 的最终值,即全是 5

在这种情况下,像你所做的那样传递切片是没有帮助的,因为这只会创建 c 的一个正确副本,而不是底层数组的副本。

尝试使用以下代码:

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)
})

来创建 c 的一个“深拷贝”。

英文:

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(&quot;Outside goroutine:&quot;, c)
	cpy := make([]int, len(c))
	copy(cpy, c)
	go func(c []int) {
		fmt.Println(&quot;Inside goroutine:&quot;, c)
	}(cpy)
})

to make a "deep copy" of c.

huangapple
  • 本文由 发表于 2017年3月7日 18:43:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/42646131.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定