std::atomic是 C++11 標準庫提供的一個模板類,用于實現原子操作。原子操作是指不會被線程調度機制打斷的操作,即這種操作一旦開始,就一直運行到結束,中間不會有任何線程切換。在多線程編程中,原子操作對于確保數據的一致性和避免數據競爭至關重要。
實際上,使用編譯器編譯的簡單語句,即使僅為簡單的輸入輸出,也是分步執行的,都不是原子操作。因此針對同一對象的訪問就有可能產生不可預料的問題。在單線程的程序中,標準庫提供的操作通常已經解決了這些問題。但在多線程環境中,如果多個線程同時訪問共享數據依然要考慮這類問題。一般的,可以使用互斥量就可以解決這個隱患。但是,這個方法往往很影響執行的效率。因此,針對一些僅對單個變量的共享數據的訪問,可以考慮使用原子操作來實現多線程安全的同時提高效率。
#include<iostream>
#include<thread>
#include<future>//使用原子操作要
using namespace std;int a = 0;//std::atmoic<int> a=0;原子操作void mythread()
{for (int i = 0; i < 10000; i++){a++;}
}
int main()
{thread myth(mythread);thread myth2(mythread);myth.join();myth2.join();cout << a << endl;//輸出結果往往是10000到20000中間的某個值。}
#include<iostream>
#include<thread>
#include<future>
using namespace std;std::atomic<bool> myend = false;void mythread()
{std::chrono::milliseconds dura(1000);while (myend == false){cout <<this_thread::get_id()<< "正在執行" << endl;std::this_thread::sleep_for(dura);}cout <<this_thread::get_id()<< "執行結束" << endl;return;
}
int main()
{thread myth(mythread);thread myth2(mythread);std::chrono::milliseconds dura(5000);std::this_thread::sleep_for(dura);myend = true;myth.join();myth2.join();}