Search code examples
c++dictionarysetreadwritelock

Thread safety of std:map and std:set


Possible Duplicate:
Do I need to protect read access to an STL container in a multithreading environment?

If some thread reading :set or :map when another thread writing to this set or map, what will happen? Exception?

Now i use read-write locks, but i want to remove locks, because writining operations are not often and reading operation very often.


Solution

  • Race conditions will happen: depending on the CPU's ordering of the things done, you will receive different results each time. If an iterator is invalidated (by e.g. deleting an item in one thread and the other thread has an iterator pointing to that now invalid memory) and then used in the other thread, you will get undefined behavior, so be wary of dead babies, clay golems, and haunts, along with the more likely segfaults, delayed segfaults, and runtime crashes.

    C++11 introduces mutex and other threading facilities: guard your reads and writes with those if you must.