C++ call_one多线程调用只执行一次可用于初始化
#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; }