问题
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