std::call_once 确保这个函数只会被调用一次。
#include <thread>
#include <mutex>
#include <iostream>
#include <unistd.h>
std::once_flag flag1;
inline void hi(int i){
std::cout << "Simple example: called once "<< i << std::endl;
}
void simple_do_once()
{
std::call_once(flag1,hi,100);
}
int main() {
simple_do_once();
simple_do_once();
simple_do_once();
}
本文通过一个简单的示例介绍了std::call_once的功能及其使用方法。std::call_once确保指定的函数仅被执行一次,即使在多线程环境中也是如此。示例展示了如何使用std::once_flag来控制函数的单一调用。
814

被折叠的 条评论
为什么被折叠?



