boost::atomic

#include "stdafx.h"
#include <iostream>
#include <boost/thread.hpp>
#include <boost/atomic.hpp>

int main(int, char*[])
{
    boost::atomic<INT32> a(0);
    std::cout<<a<<std::endl;
    boost::thread t1( [&]()
    {
        for (int cnt=0;cnt<100000;cnt++)
        {
            a += 1;
        }
    } );
    boost::thread t2( [&]()
    {
        for (int cnt=0;cnt<100000;cnt++)
        {
            a -= 1;
        }
    });
    t1.join();
    t2.join();
    std::cout<<'\t'<<a<<std::endl;
    return 0;
}
以上兩個獨立線程分別操作數據 a , 結果爲0 , 即保證了是原子操作
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章