Must I call atomic load/store explicitly?

bavaza picture bavaza · Sep 17, 2013 · Viewed 20.9k times · Source

C++11 introduced the std::atomic<> template library. The standard specifies the store() and load() operations to atomically set / get a variable shared by more than one thread.

My question is are assignment and access operations also atomic?

Namely, is:

std::atomic<bool> stop(false);
...
void thread_1_run_until_stopped()
{
    if(!stop.load())
        /* do stuff */
}

void thread_2_set_stop()
{        
    stop.store(true);
}

Equivalent to:

void thread_1_run_until_stopped()
{
    if(!stop)
        /* do stuff */
}

void thread_2_set_stop()
{        
    stop = true;
}

Answer

Andrew Tomazos picture Andrew Tomazos · Sep 17, 2013

Are assignment and access operations for non-reference types also atomic?

Yes, they are. atomic<T>::operator T and atomic<T>::operator= are equivalent to atomic<T>::load and atomic<T>::store respectively. All the operators are implemented in the atomic class such that they will use atomic operations as you would expect.

I'm not sure what you mean about "non-reference" types? Not sure how reference types are relevant here.