C++ 0x std::async 的应用

 1 #include <iostream>
 2 #include <thread>
 3 #include <mutex>
 4 #include <vector>
 5 #include <algorithm>
 6 #include <future>
 7 using namespace std;
 8 
 9 /*
10     知识点:
11         this_thread : 当前线程
12         chrono::system_clock::now() : 系统的当前时间点
13         future<void> async(std::launch::async,[](){...}) : 启动一个任务,返回的是一个 future 但一般直接 auto
14         this_thread::sleep_for(chrono::seconds(1))  : 将当前线程休眠1秒
15         chrono::duration_cast<chrono::milliseconds>(end - begin).count()  :  计算两个时间点之间的差值
16 */
17 
18 // 打印出当前线程的 ID
19 void PrintThreadID(const char* name) {
20     cout << name << " Thread id is " << this_thread::get_id() << endl;
21 }
22 
23 int main() {
24     // 得到开始时的系统时间
25     auto begin = chrono::system_clock::now();
26 
27     /*
28     可以通过stl::async函数的第一个参数控制任务的并行方式,它有如下三个取值:
29         launch::async     :   异步方式。这个方式下,所有任务都会新启动一个线程执行
30         launch::deferred  :   同步方式。 这个方式下,任务不会新启动线程,串行在创建任务的线程中执行。
31         launch::any       :   综合方式。 这个方式下,会复用创建任务的线程。 (默认值)
32     */
33 
34     // 启动第一个任务 
35     auto task1 = async([]{
36         PrintThreadID("Task1");
37         this_thread::sleep_for(chrono::seconds(1));
38         return 3;
39     });
40 
41     // 启动第二个任务
42     auto task2 = async([]{
43         PrintThreadID("Task2");
44         this_thread::sleep_for(chrono::seconds(1));
45         return 5;
46     });
47 
48     // get() 方法,本身就是
49     cout << task1.get() + task2.get() << endl;
50 
51     // 得到结束时的系统时间
52     auto end = chrono::system_clock::now();
53 
54     // 这里是计算开始与结束之间的时间差
55     cout << "Spend Time : " << chrono::duration_cast<chrono::milliseconds>(end - begin).count() << endl;
56 
57     return 0;
58 }

 

posted @ 2013-12-05 11:04  easyfrog  阅读(533)  评论(0编辑  收藏  举报