原子操作 std::atomic<int>

std::atomic<T>模板类可以使对象操作为原子操作,避免多线程竞争问题;请看如下代码,一目了然

原子操作:
可以把原子操作理解为一种:不需要用到互斥量加锁(无锁)技术的多线程编程方式
多线程中不会被打断的程序执行片段

互斥量:加锁一般针对一个代码段(几行代码)
原子操作:针对的一般都是一个变量,而不是一个代码段
一般指“不可分割的操作”
std::atomic来代表原子操作,std::atomic是个类模板。其实std::atomic这个东西是用来封装某个类型的值的

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;
};

猜你喜欢

转载自blog.csdn.net/rukawashan/article/details/125139314