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?