在多线程环境下保证某个函数近被调用一次。
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
std::once_flag flag;
void do_once()
{
std::call_once(flag, []()
{
std::cout << "Called once" << std::endl;
});
std::cout << "hello" << std::endl;
}
int main()
{
std::thread t1(do_once);
std::thread t2(do_once);
std::thread t3(do_once);
t1.join();
t2.join();
t3.join();
return 0;
}
输出结果:
注意输出结果,进lambda表达式中的内容被执行了一次,hello被打印了三次