为了保证在多线程环境中某个函数仅会被调用一次,可以使用 std::call_once 保证函数只能被调用一次。
使用 std::call_once 时需要一个 std::once_flag 做为 call_once 的入参。
std::once_flag onceFlag;
void doOnce()
{
std::call_once(onceFlag, []() {
std::cout << "Called one time" << std::endl;
}
);
}
int main()
{
std::vector<std::thread> thVec(10);
for (int i = 0; i < 10; ++i)
{
thVec[i] = std::move(std::thread(doOnce));
}
for (auto& th : thVec)
{
th.join();
}
}
/*
// ---------------------------------------------------------
// output
// ---------------------------------------------------------
Called one time
*/