-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParallelAsync.cpp
71 lines (57 loc) · 1.58 KB
/
ParallelAsync.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Example of processing multiple task chains in parallel using C++ 11 async()
//
// Complier: Visual Studio 2013 (v120)
#include "stdafx.h"
#include <future>
#include <iostream>
#include <functional>
#include <thread>
#include <chrono>
using namespace std;
namespace parallel_futures {
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::duration<double, std::milli> Milliseconds;
void spin(int ms){
auto t1 = Clock::now();
while (true){
auto t2 = Clock::now();
auto tt = (t2 - t1);
Milliseconds res = Clock::duration(1);
if (tt.count() * res.count() > ms)
break;
}
}
future<long> taskA(long i) {
// Without specifying a launch policy it's up to the complier
// to chose to execute async or deferred (sync).
return async([](long i) { i += 10; spin(10000); return i; }, i);
}
future<long> taskB(long i) {
return async([](long i) { i *= 10; spin(15000); return i; }, i);
}
long taskC(long i) {
spin(5000);
return i * 100;
}
void run() {
// Start tasks in parallel
auto a = taskA(100);
auto b = taskA(100);
auto c = taskA(100);
auto d = taskB(100);
auto e = taskB(100);
auto f = taskB(100);
// Give main thread meaningful work to do instead of just blocking
auto g = taskC(100);
// gather parallel results.
auto result = a.get() + b.get() + c.get() + d.get() + e.get() + f.get() + g;
cout << "Answer is " << result << endl;
}
}
int main()
{
parallel_futures::run();
cout << "[Press enter to exit]" << endl;
cin.ignore();
return 0;
}