douwen2158
2017-12-01 00:47
浏览 27
已采纳

在循环迭代器变量上使用goroutines

I was reading that goroutines on loop iterators often result in the last value in the loop assignment being used for every iteration. E.g. https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables

However, does this only happen for closures, e.g. with anonymous functions?

I can't seem to reproduce the issue with this example https://play.golang.org/p/lpZ-yD1mHu

When I use an anonymous function like this, it recreates the issue https://play.golang.org/p/mDa0Z6mUP8

图片转代码服务由CSDN问答提供 功能建议

我读到循环迭代器上的goroutine通常会导致循环赋值中的最后一个值用于每次迭代。 例如。 https://github.com/golang/ go / wiki / CommonMistakes#using-goroutines-on-loop-iterator-variables

但是,这仅发生在闭包时,例如

我似乎无法通过此示例重现该问题 https://play.golang.org/p/lpZ-yD1mHu

当我使用这样的匿名函数时,它会重新产生问题 https://play.golang.org/p/mDa0Z6mUP8

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • du718589 2017-12-01 01:03
    已采纳

    However, is this only a problem for closures, e.g. with anonymous functions?

    Yes. The difference between

    go speak(c)
    

    and

    go func() {
        speak(c)
    }()
    

    is, the former calls speak with the value of c in a new goroutine. In the latter one, however, the anonymous function captures not the value of c but the variable c itself (by reference¹) and, at some later point in time, calls speak with whatever value c has at this point in time.

    ¹: There are no "references" in golang, I'm not sure how this is exactly implemented, but it is as if they reference the original variable.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题