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.

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

报告相同问题?

悬赏问题

  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 flask项目,怎么使用AJAX传数据库数据到echarts图表的data里,实现异步加载数据。
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题