Search code examples
c++multithreadinglockinglock-free

C++ (CAS-like) synchronization on getter and setter of user defined types


Suppose there is a user defined class MyClass that has a setter and a getter function.

class MyClass {
    int m_value;
    public:
        void set(int value)
        { m_value = value; }

        int get() const
        { return m_value;}
};

And there is a function increment() that can increase the value of the object by 1, which may be invoked in multiple threads.

void increment(MyClass& myClass)
{
    myClass.set(myClass.get() + 1);
}

What is the best way to make this function thread-safe? By just using a lock? Is there any way to achieve it by using some CAS-like operations?


Solution

  • If you're using C++11, you could just use std::atomic<int> which provides atomic load, store and increment which seems to be everything you need.

    I suspect you don't need atomics though as in most cases they will be slower than your basic mutex.

    See this other question before you make your decision.