#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <algorithm>
#include <future>
using namespace std;
/*
知识点:
this_thread : 当前线程
chrono::system_clock::now() : 系统的当前时间点
future<void> async(std::launch::async,[](){...}) : 启动一个任务,返回的是一个 future 但一般直接 auto
this_thread::sleep_for(chrono::seconds(1)) : 将当前线程休眠1秒
chrono::duration_cast<chrono::milliseconds>(end - begin).count() : 计算两个时间点之间的差值
*/
// 打印出当前线程的 ID
void PrintThreadID(const char* name) {
cout << name << " Thread id is " << this_thread::get_id() << endl;
}
int main() {
// 得到开始时的系统时间
auto begin = chrono::system_clock::now();
/*
可以通过stl::async函数的第一个参数控制任务的并行方式,它有如下三个取值:
launch::async : 异步方式。这个方式下,所有任务都会新启动一个线程执行
launch::deferred : 同步方式。 这个方式下,任务不会新启动线程,串行在创建任务的线程中执行。
launch::any : 综合方式。 这个方式下,会复用创建任务的线程。 (默认值)
*/
// 启动第一个任务
auto task1 = async([]{
PrintThreadID("Task1");
this_thread::sleep_for(chrono::seconds());
return ;
});
// 启动第二个任务
auto task2 = async([]{
PrintThreadID("Task2");
this_thread::sleep_for(chrono::seconds());
return ;
});
// get() 方法,本身就是
cout << task1.get() + task2.get() << endl;
// 得到结束时的系统时间
auto end = chrono::system_clock::now();
// 这里是计算开始与结束之间的时间差
cout << "Spend Time : " << chrono::duration_cast<chrono::milliseconds>(end - begin).count() << endl;
return ;
}