문제

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