Search code examples
c++c++11atomicstdatomic

What operations on a c++ 11 atomic variable are actually atomic?


I'm reading the cpp reference manual on std::atomic (https://en.cppreference.com/w/cpp/atomic/atomic) and I'm confused about the exact operations that are actually executed atomically.

The main operations I'm having trouble with:
operator=, operator+, and operator+=
I know that these operations are defined for the template I'm just unsure if and when they actually are atomic. I'd appreciate help understanding when an operation on such a variable is atomic and not.

Edit:
I've read the question referenced here: What exactly is std::atomic? and I'm still confused. For example, say a is an atomic int. Is a+=100 equivalent to a.fetch_add(100)?
In the same line of questioning, is a.load(100) equivalent to a=100?


Solution

  • After watching @Treebeard's link https://www.youtube.com/watch?v=ZQFzMfHIxng (watch minutes 13-15 for the relevant information)
    Any operation performed on an atomic variable is atomic. However, the same line can contain more than one operation in it.
    So for example given the following code:

    std::atomic<int> a = 1;  
    std::atomic<int> b = 1;   
    auto c = std::atomic<int>(0);  
    c = a + b;  
    

    the last line is not an atomic operation, as a+b is in itself atomic, operator= is in itself atomic. However together they constitute 2 operations, which together are not atomic. To conclude, I'd recommend using the template's explicit functions such as load(), fetch_add(), and store(), instead of using standard overloaded operators, as these can be guaranteed to be executed atomically.