1. 简介
std::call_once
的作用是,确保在多个线程中同时调用 call_once
时,只有一个线程能够成功执行 func
函数,而其他线程则会等待该函数执行完成。
注意
: std::call_once 只能在子线程中使用,在主线程中使用会报错
template<class Callable, class... Args>
void call_once(std::once_flag& flag, Callable&& func, Args&&... args);
flag
是一个 std::once_flag
类型的对象,用于标记函数是否已经被调用;
func
是需要被调用的函数或可调用对象;
args
是函数或可调用对象的参数。
void test_call_once() {
cout << "test call_once" << endl;
}
void test_fun_time() {
cout << "test begin" << endl;
std::call_once(once_flg, test_call_once);
cout << "test after" << endl;
}
int main()
{
std::thread th1(test_fun_time);
std::thread th2(test_fun_time);
std::thread th3(test_fun_time);
th1.join();
th2.join();
th3.join();
return 0;
}
根据运行结果可以发现 std::call_once
只会被执行一次,只是执行到这的时候等待其他线程执行完之后,再接着往下执行。
2. 使用场景
- 多线程下的单例模式