1、 TicToc 类
这个类以前就写过,在我的文章里有,目的是打印逝去的时间,如下所示:
class TicToc
{
public:
TicToc()
{
tic();
}
void tic()
{
start = std::chrono::system_clock::now();
}
double toc()
{
end = std::chrono::system_clock::now();
std::chrono::duration elapsed_seconds = end - start;
start = end;
return elapsed_seconds.count() * 1000;
}
private:
std::chrono::time_point start, end;
};
2、消耗时间的操作
int result_future()
{
int i=0,ret = 0;
std::this_thread::sleep_for(std::chrono::seconds(2));
return ret + 1;
}
用sleep 2 秒来代表消耗时间的操作
主函数使用异步调用方法:
std::future result = std::async(result_future);
当我们使用result.get()的时候,会阻塞操作,从时间函数的计算上可以看出来,再调用这个函数之前,我们可以继续往下走,一直走到我们确实需要结果的时候,调用get,result_future如果需要2秒时间,我们主函数小于2秒,那么这个总时间还是2秒左右。
使用promise,可以省去我们在另外一个线程中和主线程的通信,直接让其get,就能阻塞,在get之前,我们依然可以执行我们要执行的指令。
int main()
{
TicToc tt;
std::future result = std::async(result_future);
printf("this is a test\n");
printf("this is another test\n");
for (int i = 0; i
关注
打赏