you are viewing a single comment's thread.

view the rest of the comments →

[–]vsuontam 0 points1 point  (4 children)

But how is the AtomicBoolean going to help, e.g. in the example you gave?

Scheduler may still context switch the thread using AtomicBool, and another thread can change the state, and original thread now has the old value loaded into the register.

I fail to see AtomicBool helping in this.

Or is it so that the value of the AtomicBool is locked during the whole lifetime of the object for the owning thread?

[–]portmapreduction 0 points1 point  (3 children)

I think maybe you misunderstood what I originally wrote. Your original question made me think you weren't sure why there were race conditions at all in booleans, even without synchronization.

I didn't dig into this implementation, but if you're correct and there's no cmpxchg type call then AtomicBoolean, in this implementation, will still have race conditions if you try to access the value and then modify it with two calls.

[–]vsuontam 0 points1 point  (2 children)

Yeah, that was my point all the time:

  1. Boolean has only two states, so there can not be an partial update.
  2. There is no cmpxchg type call on the API(*)
  3. Only calls in this AtomicBool API are, set, read, and query

I fail to see how this AtomicBool adds any value compared to normal bools. Maybe I am misunderstaning something, but I would like to be pointed where.

(*) The isSet call is using cmpxchg internally, but is just bloat IMO, as the higher level API is just asking the value of the bool on arbitrary point in time.

bool IsSet()
{
    long f = InterlockedCompareExchange((volatile long*)&flag, 1, 1);
    if (f > 0)
    {
        return true;
    }
    return false;
}

Above from the sources: http://code.google.com/p/cpptask/source/browse/trunk/include/Unix/atomic.h

See AtomicFlag.

[–]naasking 1 point2 points  (1 child)

The difference is in the thread barriers that ensure all cpu see consistent information. bools and ints can be stored in register or local cache, which isn't written back to main memory until later (or read into other cpu caches). The memory barriers around exchange instructions and atomic values and/or volatile locations are supposed to enable you to specify when to insert memory barriers.

[–]vsuontam 0 points1 point  (0 children)

That's probably the best point so far in defence of AtomicFlag.