Re: Thread safety in set
Ulrich Eckhardt schrieb:
tk wrote:
From MSDN Library reference "set Class", it says "Inserting elements
invalidates no iterators, and removing elements invalidates only those
iterators that had specifically pointed at the removed elements."
Does this mean that multiple threads inserting to a set and iterating a
set is OK, as long as there is no threading removing from it?
No. While inserting elements, internal data structures can well be in a
state that wouldn't allow reading from the set. It is only before and after
these operations that a consistent state exists.
Agreed
Further, and that is an
issue often ignored by programmers, thread safety is not only about
atomicity but also about visibility, in particular in systems with multiple
CPU(-core)s.
I do not quite understand, what do you mean by visibility in this context? Cache
issues?
This seems contradicting to another referece "Thread Safety in the
Standard C++ Library" in MSDN Library:
"The container classes are vector, deque, list, queue, stack ,
priority_queue, valarray, map, multimap, set, multiset, basic_string,
bitset. For reads to the same object, the object is thread safe for
reading in the following scenarios:
From one thread at a time when no writers on other threads.
From many threads at a time when no writers on other threads.
For writes to the same object, the object is thread safe for writing from
one thread when no readers on other threads"
This is not contradicting the above. The above has nothing to do with
multithreading, it only documents required iterator invalidation rules from
the C++ standard.
Not true. This has to do everything with multithreading. It explains it all.
The relevant section for threads writing to the set is:
>> For writes to the same object, the object is thread safe for writing from
>> one thread when no readers on other threads"
That means writing to a set is only "thread-safe" for one thread thread when no
other thread is reading or writing. Which basically means every thread may use
the set, but only one thread at a time. And it means you need special guards in
your code (i.e. critical section or mutex) to ensure this condition.
Norbert