Home > Back-end >  std map access element while creating new one thread safety
std map access element while creating new one thread safety

Time:05-07

If I have a map<int, Fruit> x. On one thread I try to read the data of one element x[10].type, while on another thread I create a new element Fruit &new_fruit = x[7]. Is this thread safe? Since from what I can understand as long as it is not the same key/element it should be fine.

CodePudding user response:

You're probably referring to iterator invalidation, when you say that from what you understand, it's safe as long as you're not reading/writing to the same key from different threads.

However, thread safety doesn't work like that. Unless it is explicitly guaranteed (or proven,) you must assume that this kind of access to a data structure is unsafe. And by "this kind of access" I mean non-synchronized non-const access to the data structure and its meta-data from more than one thread.

If you need convincing, just think about the balanced binary search tree (e.g. red-black or AVL tree) that is almost always used to implement a std::map. When you insert an element (as x[7] can do,) it will re-organize (or "rotate") other nodes, and also will update the calculated heights or number of children in the nodes.

Any non-trivial datastructure/container that doesn't give you guarantees about data races and thread safety must be considered as thread-unsafe and protected with external critical sections. Unless proven otherwise. Carefully.

  • Related