duanfei1987 2019-02-07 20:12
浏览 53
已采纳

在Go Routines中迭代地图?

I am seeing some "fatal error: concurrent map iteration and map write" on some old code written a while back. I've been trying to diagnose the issue, and I ran into a block of code similar to the below playground link.

It seems wrong to me to iterate on a returned map (which is passed by reference) even if it is returned in a function with a lock.

I was looking for an explanation about why this seems to not be throwing the above error.

I understand that there are RWMutex's and sync Maps now, but this code was written a while back, and I am looking for an explanation of the functionality as opposed to improvements.

https://play.golang.org/p/_RY-QAyGE2W

I would assume that the above code would throw "fatal error: concurrent map iteration and map write", however it seems to be working with no issue.

  • 写回答

1条回答 默认 最新

  • duancan9815 2019-02-07 20:35
    关注

    This illustrates it better: https://play.golang.org/p/RiWTxBoNqwD It won't run in the playground but it crashes pretty much right away if you go run it from the commandline.

    The iteration of the map isn't protected by the mutex. Only the act of returning the map reference is protected.

    This does almost the same but the entire iteration is protected by the mutex: https://play.golang.org/p/cQNs3x_k-SL or this https://play.golang.org/p/ydjprgvF6aE

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器