This is about thread safety of std::map. Now, simultaneous reads are thread-safe but writes are not. My question is that if I add unique element to the map everytime, will that be thread-safe?
-
So, for an example, If I have a map like this
std:map<int, std::string> myMap
and I always add new keys and never modify the existing key-value, will that be thread-safe? -
More importantly, will that give me any random run-time behavior?
-
Is adding new keys also considered modification? If the keys are always different while adding, shouldn’t it be thread-safe as it modifies an independent part of the memory?
Thanks
Shiv
1) Of course not
2) Yes, I hope you’ll encounter it during testing, not later
3) Yes, it is. The new element is added in a different location, but many pointers are modified during that.
The map is implemented by some sort of tree in most if not all implementations. Inserting a new element in a tree modifies it by rearranging nodes by means of resetting pointers to point to different nodes. So it is not thread safe