dongmoxin7111 2017-03-07 10:43
浏览 23
已采纳

循环时,goroutines内部的值不正确

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.

  • 写回答

1条回答 默认 最新

  • duanfen9090 2017-03-07 11:32
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真