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

标签 go closures channel goroutine

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

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
    }
    // ...
}

我不明白为什么。这两种变体有什么区别?
我只运行 permutate在一个 goroutine 中,所以写入 channel 应该以串行方式发生,所以没有两个 goroutine 应该修改 perm一次变数。
我试图调试正在发生的事情,但我猜它是 Heisenbug因为在调试过程中,不会发生竞态,所以我猜这与 goroutine 的调度有关。

这是完整的程序(带有全局 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 通过 channel 接收到 slice 后,permutate goroutine 可以继续运行并调用下一个 nextPerm() - 如解释的那样,它修改了 slice 。这可能会在主 goroutine 使用它之前发生,也可能不会发生(甚至发生在某些事情的中间),这是一场数据竞争。所以fmt.Println(perm)可能会打印下一个排列迭代或正确的排列(或者在极少数情况下,混合两个)。

当您声明 perm在闭包内部,它是一个新变量,每次调用闭包时都会分配新的底层数组。所以没有任何东西是共享的,也没有数据被竞争。

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

关于go - 为什么闭包中本地分配的变量在外部分配时的工作方式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59227074/

相关文章:

rust - 您可以使用 impl Fn 接受任意大小的闭包作为参数吗?

go - 如何同步常量写入和周期性读取和更新

go - 重写和缩短 switch case 表达式

go - main 函数是否运行一个 goroutine?

c++ - C 的替代方案,例如为 C++ 标记和转义嵌套循环

go - 信号 goroutines 在 channel 关闭时停止

java - SocketChannel.close() 是否也关闭套接字?

rest - 如何使用证书 golang 发送 https 请求

php - 位移 : Can someone explain what this code does?

javascript - 为什么我不能在 Javascript 中滚动循环?