c++multithreadingatomicc++98

Is this the correct way to atomically read and write a bool?


A boolean flag is toggled by two threads. Does the following code make sense?

static bool ATOMIC_BOOL_READ( volatile bool& var )
{
    return __sync_fetch_and_or(&var, 0);
}

static void ATOMIC_BOOL_WRITE(volatile bool& var, bool newval )
{
    __sync_bool_compare_and_swap( &var, !newval, newval);
}

Note a few things:

Update:

The fundamental question I want to ask is: Whats the difference between atomicity and memory barrier? If Thread A is executing an atomic builtin on variable foo, then Thread B cannot do ANYTHING on variable foo; hence creating a memory barrier?


Solution

  • Atomics are intrinsically non-portable and these are GCC extensions that might not exist anymore in the future and won't work on other compilers.

    You should read the rest of the answer only once you understood completely the above statement.

    A notable fact is that ALL machines existing have always guaranteed that access to data up to a certain size is atomic. This comes from the basic notion that data in memory and in the system bus is transfered with a certain granularity. A boolean should definitively be atomic in most machines, so:

    bool ATOMIC_BOOL_READ(volatile bool* b) {
        bool v = *b;
        __sync_synchronize(); // ensure value pushed to memory
        return v;
    }
    
    void ATOMIC_BOOL_WRITE(volatile bool* b, bool v) {
        __sync_synchronize(); // read will return fresh value
       *b = v;
    }
    

    That is probably the reason why GCC does not provide simple load/store special atomic operations: they are already supposed to be atomic.