如果在併發編程過程中有一個局部變量被聲明爲static類型,該類型的變量在聲明後就已經完成初始化。對於多線程調用的函數,對於該變量就會存在條件競爭:各個線程都認爲自己是第一個初始化這個變量的線程;或者一個線程要使用這個變量的時候另外一個線程對該變量還沒有初始化完成。
在c++11中可以解決這個問題:將初始化和定義放在一個線程中,並且沒有其他線程可在初始化完成之前對其進行處理-使用std::call_once()函數進行處理。
定義於頭文件 <mutex>
template< class Function, class... Args > void call_once( std::once_flag& flag, Function&& f, Args&& args... );
功能:執行功能f一次,即使從多個線程調用.
#include <iostream>
#include <thread>
#include <mutex>
std::once_flag flag;
class my_class;
my_class& get_my_class_instance()
{
static my_class instance;//線程安全的初始化過程
return instance;
}
void do_once()
{
std::call_once(flag,get_my_class_instance);
}
int main()
{
std::thread t1(do_once);
std::thread t2(do_once);
std::thread t3(do_once);
t1.join();
t2.join();
t3.join();
}