Concurrent access to different keys in Map C++

♀尐吖头ヾ 提交于 2019-12-13 12:46:06

问题


I have two threads where one thread "A" inserts a key X to the map and the same key X is being modified by that thread "A" frequently.

At a particular point the thread "A" completes modifications to that key X and then thread "B" will read the key "X" and delete the key "X" from the map.

While the thread "B" reads and deletes the map , the thread "A" will insert and write some other keys in the map(not the same key X) concurrently.

In this case , does the map needs to be synchronized? As the thread "B" is sure that the key "X" is completely modified by thread "A" and no more concurrent modifications will be made for that key "X".


回答1:


Yes, you need synchronization.

Inserting and deletion can change internal state of the map class that can overlap with other similar operations (even if they are for different keys).

While thread A updates the object you don't need to lock the map. Map guarantees that iterators and object pointers are stable under insertions/deletions so your object won't be touched.



来源:https://stackoverflow.com/questions/32839569/concurrent-access-to-different-keys-in-map-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!