dongyan1936 2017-10-01 15:43
浏览 277
已采纳

并发写入包含Golang中另一个Map的Map

In Golang we have to sync concurrent changes to the Map. If my Map contains another Map like this:

map[string]map[string]*CustomStruct

.. do I have to use Lock in all of them when writing something?

If I'll write something into internal Map -> outer Map will also be changed, so I still have to sync outer Map's changes.

If I Lock outer Map's changes -> no one else can write into internal Map -> there is no point to Lock internal Map.

Am I right or it works in a different way and I must lock all Maps?

  • 写回答

2条回答 默认 最新

  • dongshangan2074 2017-10-01 15:59
    关注

    My understanding is that there aren't any hard and fast rules here.

    For example, you could coordinate all map writes via a mutex that's not even stored on the map, there is no inherent link between any mutex and your map - its just about how you use them to coordinate access to your data.

    Essentially if you lock individual elements you will see less contention over the locks because the locks will be acquired less often, if you use an outer lock over all maps there will be more contention as more processes will be trying to acquire the same lock which will reduce how much actual work your processes can get done.

    It's ultimately up to you to work out what works best for your use case

    Help with that:

    There is a new tool available in go 1.9 that allows you to benchmark lock contention to see what approach is most efficient for your application.

    Building and running your app with the -race flag will help determine if the locks are doing their job correctly

    You could also take a look at the new sync maps which I haven't played with yet but I understand handle this for you:

    Sync maps

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

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