I have a multi-threaded application and a shared resource std::map<KeyType, ElementType>
. I use a mutex to protect inserts, gets and removes.
My get method returns a reference to the stored element (unlocks on return), and then I do some work with that element.
Question: Is it possible that while working with the stored element reference, another thread may change the std::map
so the element will be moved to a different address and the reference will no longer be valid? (I know there are certain ADT implementations which do rearrangement of the ADT on resize).
Time complexity: k*log(n) where n is size of map, k is no. of elements inserted.
std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare .
If you mean std::map , it stores pairs of values. In each pair, the first value is called the key, and can be used to quickly look up the associated other value.
The iterator invalidation rule for associative containers (which std::map
is) says at [associative.reqmts]/9:
The insert and emplace members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.
So if one thread inserts an element, it won't affect any references to existing elements. But if it removes something, other threads may be borked. Some form of element-wise locking is in order, I'd say.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With