0

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".

Sel_va
  • 588
  • 5
  • 25
  • 1
    Take a look at this [SO answer](http://stackoverflow.com/a/15067564/5148276). You will notice that deletion/reallocation may cause data races. IMO, you should consider using [`tbb::concurrent_hash_map`](https://www.threadingbuildingblocks.org/docs/help/reference/containers_overview/concurrent_hash_map_cls.htm). – Pooja Nilangekar Sep 29 '15 at 09:00
  • I am not talking about deletion of same key that the other thread is processing.. I am deleting a key that will be no more processed, while other key insertions are happening in the map. – Sel_va Sep 29 '15 at 09:03
  • 2
    Yes; deleting a key could modify the map in ways that affect the lookup of other keys. – Davislor Sep 29 '15 at 10:02

1 Answers1

3

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.

Sorin
  • 11,863
  • 22
  • 26