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?

有帮助吗?

解决方案

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.

其他提示

Use std::mutex and enjoy

    #include <mutex>

    class MyClass 
    {
        int m_value;
        std::mutex mtx;

        void set(int value) 
        {
            mtx.lock();
            m_value = value;
            mtx.unlock();
        }

        int get() const 
        {
            return m_value;
        }
    } 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top