C++ 原子操作 std::atomic


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();

 

blog_di


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM