登录
首页 >  Golang >  Go问答

闭包中本地分配的变量与外部分配的变量之间的工作方式有何不同?

来源:stackoverflow

时间:2024-03-22 11:36:56 113浏览 收藏

在 Go 闭包中,本地分配的变量和外部分配的变量的工作方式不同。外部分配的变量在闭包的每次调用中都是共享的,可能导致数据竞争。而本地分配的变量每次调用时都会创建新的底层数组,避免了数据竞争。因此,在闭包中分配变量(而不是外部分配)可以防止数据竞争,确保闭包的正确行为。

问题内容

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

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

我不明白为什么。这两种变体有什么区别? 我只在一个 goroutine 中运行 permutate,因此写入通道应该以串行方式进行,因此任何两个 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 通过通道接收到切片后,permutate goroutine 可以继续运行并调用下一个 nextPerm() - 它会修改切片,如所解释的。在主 goroutine 使用它之前,这可能会发生,也可能不会发生(甚至可能发生在某些事情的中间),这是一个数据竞争。因此 fmt.Println(perm) 可能会打印排列的下一个迭代或正确的迭代(或者在极少数情况下,混合两个)。

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

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

以上就是《闭包中本地分配的变量与外部分配的变量之间的工作方式有何不同?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>