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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?