为什么闭包中的局部分配变量在外部分配时的工作方式不同?



我在这样的函数中有一个闭包:

func permutate(ch chan []int, numbers []int, r int) {
// ... see the full program below
perm := make([]int, r, r)
nextPerm := func() []int {
for i, ind := range indices[:r] {
perm[i] = numbers[ind]
}
return perm
}
// later writing to ch in two places:
// ch <- nextPerm()  
// ...
}

当我在闭包内分配perm变量时,这的工作方式不同:

func permutate(ch chan []int, numbers []int, r int) {
// ...
nextPerm := func() []int {
perm := make([]int, r, r)
for i, ind := range indices[:r] {
perm[i] = numbers[ind]
}
return perm
}
// ...
}

我不明白为什么。两种变体之间有什么区别? 我只在一个 goroutinepermutate中运行,因此写入通道应该以串行方式进行,因此没有两个 goroutines 应该同时修改perm变量。 我试图调试正在发生的事情,但我想这是一个 Heisenbug,因为在调试期间,竞争条件不会发生,所以我想这与 goroutines 的调度有关。

以下是完整的程序(带有全局perm变量(:

package main
import (
"errors"
"fmt"
)
func IterPermutations(numbers []int, r int) <-chan []int {
if r > len(numbers) {
err := errors.New("r cannot be bigger than the length of numbers")
panic(err)
}
ch := make(chan []int)
go func() {
defer close(ch)
permutate(ch, numbers, r)
}()
return ch
}
// an implementation similar to Python standard library itertools.permutations:
// https://docs.python.org/3.8/library/itertools.html#itertools.permutations
func permutate(ch chan []int, numbers []int, r int) {
n := len(numbers)
if r < 0 {
r = n
}
indices := make([]int, n, n)
for i := 0; i < n; i++ {
indices[i] = i
}
cycles := make([]int, r, r)
for i := 0; i < r; i++ {
cycles[i] = n - i
}
perm := make([]int, r, r)
nextPerm := func() []int {
for i, ind := range indices[:r] {
perm[i] = numbers[ind]
}
return perm
}
ch <- nextPerm()
if n < 2 {
return
}
var tmp []int
var j int
for i := r - 1; i > -1; i-- {
cycles[i] -= 1
if cycles[i] == 0 {
tmp = append(indices[i+1:], indices[i])
indices = append(indices[:i], tmp...)
cycles[i] = n - i
} else {
j = len(indices) - cycles[i]
indices[i], indices[j] = indices[j], indices[i]
ch <- nextPerm()
i = r // start over the cycle
// i-- will apply, so i will be r-1 at the start of the next cycle
}
}
}
func main() {
for perm := range IterPermutations(phaseSettings, 3) {
fmt.Println(perm)
}
}

这是一场数据竞赛。当您在闭包外部声明perm时,闭包会在每次调用时重用perm并对其进行修改。

在主 goroutine 通过通道接收切片后,permutategoroutine 可以继续运行并调用下一个nextPerm()- 如前所述,这会修改切片。这可能会也可能不会在主goroutine使用它之前发生(甚至发生在某事中间(,这是一场数据竞赛。因此,fmt.Println(perm)可能会打印下一个排列迭代或正确的排列(或者在极少数情况下,两个的混淆(。

当您在闭包中声明perm时,它是一个新变量,并且每次调用闭包时都会有新的底层数组分配。因此,没有共享任何内容,也没有数据被竞争。

注意:Go 的比赛检测器可能无法每次都检测到数据竞跑 - 因为数据竞跑可能根本不每次都发生。要了解有关种族检测器的更多信息,请参阅 https://blog.golang.org/race-detector 和 https://github.com/google/sanitizers/wiki/ThreadSanitizerAlgorithm 。

最新更新