0

Suppose the size of these containers are fixed. The array, vector and unordered_map are fully initialized with all indexes/keys possible in our setting before concurrent use.

Then in the concurrent step, only operations allowed are read and update. No delete or add are allowed. So no resize nor rehash would happen (I think).

Under this scenario, are these containers thread-safe? Any example they would break?

I have read some questions like 1 and 2 that make me believe they would be thread-safe if each thread writes to a distinct element. 3 says STL containers are only thread-safe when one thread is writing at a time and no other is reading. I am having a hard time understanding why multiple threads update a same element is not safe? As long as the memory is aligned (no weird partial results), it's just last write wins right?

oceanlau
  • 3
  • 1
  • Multiple threads reading and writing a simple object is not thread-safe. _"multiple threads update a same element"_ is not thread-safe for the same reason. _"it's just last write wins right?"_ No, the result could be a mix of different write operations. – Thomas Sablik Aug 25 '20 at 19:29
  • *I am having a hard time understanding why multiple threads update a same element is not safe?* If two threads write to an object, what happens if both threads write at the same time? What value should you get? – NathanOliver Aug 25 '20 at 19:29
  • Ignore containers, they're just a distraction. You have a global int which you write to from 2 threads at the same time. The standard says this is undefined behaviour so you cant do it. No you won't get 'last write wins' as that's not what the language standard defines. Thinking of how cpus/computers/memory works is the wrong question to ask - you need to know the language guarantees and in this case they say its wrong. – Mike Vine Aug 25 '20 at 19:59
  • Thank you for the explanations! Looks like the fundamental problem is there is no atomic guarantee so we would need a unique lock for concurrent read/write or write/write situation. – oceanlau Aug 25 '20 at 20:10

0 Answers0