如果要保證某個函數(shù)在多線程的環(huán)境下只被調用一次宝剖,可以使用callonce拯钻,一個典型的場景就是初始化吉嚣。callonce需要once_flag作為入?yún)⒐刍啊J褂脮r需要包含頭文件<mutex>
#include<iostream>
#include<thread>
#include<mutex>
std::once_flag flag;
std::once_flag flag2;
void f() {
std::cout << "call once" << std::endl;
}
void do_once() {
std::call_once(flag, f);
std::call_once(flag2, f);
}
int main() {
//error std::call_once不可作為參數(shù)
//std::thread t1(std::call_once(flag, []{std::cout << "call once" << std::endl;}));
std::thread t1(do_once);
std::thread t2(do_once);
t1.join();
t2.join();
}
其輸出為
call once
call once