欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++ 原子操作 std::atomic<T>

程序员文章站 2024-03-18 08:41:40
...
class Test
{
public:    
    Test() = default;

    void CThreadFunc()
    {
        for (int i = 0; i < 10000; ++i)
        {
            //std::lock_guard<std::mutex> lck(Test::m_s_ivalue_mutex); //m_iValue需要加锁才可正常工作
            m_iValue++;

            m_atomic_value++;//不加锁,也可正常工作
        }
    }

    void Start()
    {
        std::vector<std::thread> threads;
        for (int i = 0; i < 10; ++i)
        {
            threads.push_back(std::thread(&Test::CThreadFunc, this));
        }

        for (auto& th : threads)
        {
            if (th.joinable())
            {
                th.join();
            }
        }     std::cout << "m_iValue:" << m_iValue << ", m_atomic_value:" << m_atomic_value << std::endl;
    }

private:
    int m_iValue = 0;
    std::atomic<int> m_atomic_value = 0;//sta::atomic<T> 原子操作
    static std::mutex m_s_ivalue_mutex;
};

 

相关标签: std