user695652 user695652 - 2 days ago 5
C++ Question

threadsafety vs Iterator validity

I have two threads:


  • Thread A inserting into an
    std::map

  • Thread B removing from an
    std::map



Since
std::map::erase
and
std::map::insert
keep all iterators of the map valid, I don't seem to understand how a race condition could occur in this scenario.

Answer

Comments are saying the right thing. I will combine them with your statement:

std::map::erase and std::map::insert keep all iterators of the map valid only if they are executed sequentially.

If they are executed in parallel, one thread (when it starts its work) may face a partially modified object (the other thread is working on it). The result of action on a partially modified object is undefined. This is the source of the problem.

If you synchronize access to your object with say mutex everything will work fine. Containers do not have built in synchronization because this would significantly slow down their work while this is needed only sometimes.

Comments