Search code examples
c++multithreadingc++11atomic

C++ std::atomic for user defined data types


I am unable to understand and write up a code related to below Atomic Library functionality for user defined data type:

std::atomic::compare_exchange_weak, std::atomic::compare_exchange_strong

bool compare_exchange_weak( T& expected, T desired,
                            std::memory_order success,
                            std::memory_order failure );

bool compare_exchange_strong( T& expected, T desired,
                              std::memory_order success,
                              std::memory_order failure );

So if I have below trivial class how can I use compare_exchange_weak / compare_exchange_strong Atomic library methods on that trivial class?

class A
{
public:
    void Show()
    {
        std::cout << "Called\n";
    }
};

I am unsure what expected / desired values we should set in the method for user defined datatype - class A for example?


Solution

  • Your class has no data, hence there is no need to use std::atomic<A>. If you want to know how to use std::atomic with UDT, You may add a member data and then use the following code

    #include <iostream>
    #include <atomic>
    
    class A
    {
    public:
        int a;
        void Show()
        {
            std::cout << a << "\n";
        }
    };
    
    int main( ) {
        A a1{1};
        A a2{2};
        std::atomic<A> atomicA{a1};
        atomicA.load().Show();//the original atomicA
        atomicA.compare_exchange_strong(a2, A{2});// this makes no change
        atomicA.load().Show();
        atomicA.compare_exchange_strong(a1, A{2});//this changes atomicA
        atomicA.load().Show();
    
    }
    
    

    Note that not all UDT can gain a real atomic behavior (it may be achieved using locks). to make sure that your atomic has a real atomic behavior you can use atomicA.is_lock_free().