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

在循环迭代器变量上使用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

  • 写回答

1条回答 默认 最新

  • 普通网友 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.

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

报告相同问题?

悬赏问题

  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态