Alex Rivera | Logout

std::atomic<int> decrement and comparison

Asked 2011-10-26T18:47:27.627
27

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.

Edit
Report

1 Answer

-2

No it is not possible that more than one thread enters the block, given your constraints. But neither is it guaranteed that any thread ever enters this block:

thread A: decrement myint to 0

thread B: decrement myint to -1

thread A: compare to 0 -> false -> don't enter (and neither anyone else)

If this is a problem (which I assume), then this code won't work (at least not always).

answered 2011-10-26T21:59:02.773

Your Answer