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条)

报告相同问题?