Prev: Continuation of the MacOS networking thread...
Next: Continuation of the MacOS networking thread...
From: Maxim Yegorushkin on 26 Dec 2009 16:10 On 23/12/09 00:09, novickivan(a)gmail.com wrote: > lets say I have > > unsigned int x = 0; > > And the code > > x++; > > Is run a total of 1 million times but the million times is divided > across many threads. > > If i try to read the value of x am i guaranteed to get a value between > 0 and 1 million. > > The subtle question here is, are reads and writes of a variable > atomic? The C and C++ standards do not guarantee that assignment is an atomic operation unless the left operand has type sig_atomic_t. A particular compiler can provide more guarantees, however, portable code can not rely on that. Please note, however, that threads are outside of the scope of current C and C++ standards. So that there is an unlikely chance that their definition of atomic might be not thread-safe. C++0x will address threading and provide atomics library. Till it is widely available portable code has to rely on mechanisms outside of the scope of C and C++ standards, such as gcc atomic built-ins (http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Atomic-Builtins.html) or other atomics libraries, such as Intel TBB and its atomic<T> template. > Do i have to worry that i am reading the variable while it is > being updated and might get total garbage such as 9 million as the > value when i read it. Or is the worst case that i missed some > increments because the increment on 1 thread was done without taking > into account the updates from another thread? When you are using thread-safe atomics, writes are atomic with respect to other threads, i.e. no worries ;) -- Max |