std::call_once提供一种方式,可以保证其实例绑定的函数,能且仅能被执行一次:
template <class Fn, class... Args>
void call_once (once_flag& flag, Fn&& fn, Args&&... args);
flag:仅可执行一次的对象,其生命周期要比所在的线程长
Fn:执行函数
args:执行函数的可变参数
当多个线程使用同一个flag对象去调用函数call_once时,仅有一个线程可以真正的完成对函数Fn的调用,其他的线程会被阻塞,直到函数Fn返回:
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
using namespace std;
unsigned long getTime() //获得时间戳
{
return chrono::system_clock::now().time_since_epoch().count()/chrono::system_clock::period::den;
}
void doTask(int id)
{
cout<<getTime()<<" doTask:"<<id<<" begin"<<endl;
this_thread::sleep_for(chrono::seconds(2));
cout<<getTime()<<" doTask:"<<id<<" end&