c++atomicstdatomic

atomically compare and store if not equal


How to atomically compare and store the value it's compared with if they aren't equal. The below code is not able to achieve this operation atomically

#include <iostream>
#include <atomic>

int main() {
    static std::atomic<int> AT(23);
    int a = 32;
    
    if (AT.load() != a) {
        std::cout << "not equal" << std::endl;
        AT.store(a);
    }
}

Solution

  • You don't need to check the value in advance if all you want to know is whether setting it has changed the value, you can just use the exchange function to set the new value:

    #include <iostream>
    #include <atomic>
    
    int main() {
        static std::atomic<int> AT(23);
        int a = 32;
        
        if (AT.exchange(a) != a) {
            std::cout << "not equal" << std::endl;
        }
    }
    

    If the value hasn't changed, resetting it to the same value shouldn't matter.