c++11 線程原子變量

#include
#include <thread>
#include <vector>
#include <functional>
#include <atomic>
void func(int& _counter)
{
  for(int i=0; i<10000; i++)
    ++_counter;
}




void func2(std::atomic<int>& _counter)
{
  for(int i=0; i<10000; i++)
    ++_counter;
}


int main()
{
  //int counter = 0;
  std::atomic<int> _counter(0);  //使用原子變量
  std::vector<std::thread> _threads;
  for(int i=0; i<10; i++)
    _threads.push_back(std::thread{func2, std::ref(_counter)}); //要符合線程初始邏輯


  for(auto& _t : _threads)
  {
    _t.join(); //防止主線程退出
  }




  std::cout<<"result:="<< _counter<<std::endl;
  return 0;

}


歡迎加入Jack_Li的金融交易-知識星球,這裏有高大上的金融業務學習和編程知識學習,讓你掌握時下最火爆的兩門top行業信息,在這裏你可以獲得Jack_Li的經驗,獲得Jack_Li同學的內部推薦(證券公司,基金公司,大型金融機構等,入圈5天后發佈),歡迎加入(請掃二維碼):


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章