std:call_once是C++11引入的新特性,如需使用,只需要#include
相对来说,std::call_once用法比较简单,配合std::once_flag即可实现
C++ call_one多线程调用只执行一次可用于初始化_c++ 只运行一次的线程-CSDN博客
- #include <iostream>
- #include <thread>
- #include <mutex>
-
- void SystemInit(){
- cout << "SystemInit......" << endl;
- }
-
- void SystemInitCallOnce(){
- // 记录调用的状态
- static once_flag flag;
- // 多次调用只执行一次
- call_once(flag,SystemInit);
- }
- int main(int argc,char* argv[])
- {
- for(int i = 0;i<10;i++)
- {
- thread th(SystemInitCallOnce);
- th.detach();
- }
- cout << "等待10s...."<< endl;
- this_thread::sleep_for(10000ms);
- cout << "等待10s结束"<< endl;
- return 0;
- }