std::call_once 的作用是很简单的,就是保证函数或者一些代码段在并发或者多线程的情况下,始终只会被执行一次。比如一些初始化函数,多次调用可能导致各种奇怪问题。
需要包含头文件:#include <mutex>
template <class Fn, class... Args>
void call_once(once_flag & flag, Fn && fn, Args &&...args);
参数
给个例子:
#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();
}
只会输出一行:Simple example: called once