C++11
std::call_once的作用是很簡單的, 就是保證函數(shù)或者一些代碼段在并發(fā)或者多線程的情況下,始終只會被執(zhí)行一次。比如一些init函數(shù),多次調(diào)用可能導致各種奇怪問題
#include <iostream>
#include <thread>
#include <mutex>
std::once_flag flag1;
void simple_do_once()
{
std::call_once(flag1, [](){ std::cout << "Simple example: called once\n"; });
}
int main()
{
std::thread st1(simple_do_once);
std::thread st2(simple_do_once);
std::thread st3(simple_do_once);
std::thread st4(simple_do_once);
st1.join();
st2.join();
st3.join();
st4.join();
}
Output:
Simple example: called once