Question

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.

Was it helpful?

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.

OTHER TIPS

Standard containers aren't thread-safe, and they aren't specified to have "fail fast" iterators in the Java sense. So there are at least two things that can go wrong with unprotected concurrent access:

  1. a data race on the container, which is undefined behavior
  2. one thread invalidates an iterator and later another thread uses an equal-valued iterator. This is also undefined behavior but it isn't necessarily a data race, and would be a bug in a single-threaded program too. It's just a bit easier to lose track of multiple iterators on the same container when they're used in different threads.

One might say that the C++ philosophy is to "succeed fast", and never mind what happens when the programmer fails ;-). Hence there are no built-in locks that would be redundant for many users. Instead it's your problem -- you'd rather be unhappy that the locks are slowing down this program, than unhappy that they're slowing down this program and every other program you ever wrote that used set, even when the set isn't concurrently accessed.

writing operations are not often and reading operation very often.

That's exactly the situation where reader-writer locks should perform well. The only way you can improve your situation is if you can reduce the write operations from "not often" to "never", which presumably you can't.

mutexs,locks.... brrr try to use free lock containers. for example Intel "threading building blocks" aka TBB http://threadingbuildingblocks.org/files/documentation/a00130.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top