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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?