C++ 原子操作 std::atomic<T>
std::atomic<T>模板类可以使对象操作为原子操作,避免多线程竞争问题;请看如下代码,一目了然:
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; };
执行:
Test test;
test.Start();