On the following code:
std::atomic<int> myint; //Shared variable
//(...)
if( --myint == 0) {
//Code block B
}
Is it possible that more than one thread access the block I named "Code Block B"?
Please consider that overflow will not happen, that the 'if' is being executed concurrently by more than one thread, that the only modification to myint in the whole program is the --myint inside the if and that myint is initialized with a positive value.
C++0x paper N2427 (atomics) states roughly the following. I've changed the wording slightly so its easier to read for the specific decrement situation, the parts I changed are in bold:
Effects: Atomically replace the value in object with result of the decrement applied to the value in object and the given operand. Memory is affected as per order. These operations are read-modify-write operations in the sense of the "synchronizes with" definition in [the new section added by N2334 or successor], and hence both such an operation and the evaluation that produced the input value synchronize with any evaluation that reads the updated value.
Returns: Atomically, the value of object immediately before the decrement.
The atomic operation guarantees that the decrement operator will return the value that the variable held immediately before the operation, this is atomic so there can be no intermediate value from updates by another thread.
This means the following are the only possible executions of this code with 2 threads:
(Initial Value: 1)
Thread 1: Decrement
Thread 1: Compare, value is 0, enter region of interest
Thread 2: Decrement
Thread 2: Compare, value is -1, don't enter region
or
(Initial Value: 1)
Thread 1: Decrement
Thread 2: Decrement
Thread 1: Compare, value is 0, enter region of interest
Thread 2: Compare, value is -1, don't enter region
Case 1 is the uninteresting expected case.
Case 2 interleaves the decrement operations and executes the comparison operations later. Because the decrement-and-fetch operation is atomic, it is impossible for thread 1 to receive a value other than 0 for comparison. It cannot receive a -1 because the operation was atomic... the read takes place at the time of the decrement and not at the time of the comparison. More threads will not change this behavior.