头文件 #include 。
函数原型:
template<class Callable, class... Args>
void call_once(std::once_flag& flag, Callable&& f, Args&&... args);
flag:标志对象,用于指示 f 是否已调用过。f:要调用的可调用对象。args:传递给 f 的参数。作用:保证可调用对象 f 只被执行一次,即使同时从多个线程调用。
注意事项:
#include
#include
#include
std::once_flag flag1, flag2;
void simple_do_once()
{
std::call_once(flag1, []() { printf("only call once\n"); });
}
void may_throw_function(bool do_throw)
{
if (do_throw) {
printf("throw, try again...\n");
throw std::exception();
}
printf("no throw, call once\n");
}
void do_once(bool do_throw)
{
try {
std::call_once(flag2, may_throw_function, do_throw);
} catch (...) {
}
}
int main()
{
std::thread st1(simple_do_once);
std::thread st2(simple_do_once);
st1.join();
st2.join();
std::thread t1(do_once, true);
std::thread t2(do_once, false);
std::thread t3(do_once, true);
t1.join();
t2.join();
t3.join();
}