-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsync.cpp
More file actions
81 lines (66 loc) · 1.73 KB
/
Async.cpp
File metadata and controls
81 lines (66 loc) · 1.73 KB
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
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <thread>
#include <chrono>
#include <future>
using namespace std;
void timeTakingFunc(int duration)
{
cout << "Started time consuming task thread: " << this_thread::get_id() << endl;
this_thread::sleep_for(chrono::seconds(duration));
cout << "Done with time consuming task: " << this_thread::get_id() << endl;
}
void square(int x)
{
cout << x * x << " : " << this_thread::get_id() << endl;
}
int main()
{
cout << "Starting program... : " << this_thread::get_id() << endl;
/*
- Offload time taking func to another thread
- this prevents blocking of main thread of execution
*/
future<void> fut = async(timeTakingFunc, 5);
/*
- below func taking same duration as above
- here by the time this func is finished above func is also finished in another thread
*/
timeTakingFunc(5);
for (int i = 1; i < 10; i++)
{
square(i);
}
fut.get(); // synchronization point
cout << "Finished program...: " << this_thread::get_id() << endl;
return 0;
}
/*
OUTPUT BEFORE USING ASYNC
Starting program... : 140645445473216
Started time consuming task thread: 140645445473216
Done with time consuming task: 140645445473216
1
4
9
16
25
36
49
64
81
Finished program...: 140645445473216
=================================================================================================================
Starting program... : 140661222073280
1 : 140661222073280
4 : 140661222073280
9 : 140661222073280
16 : 140661222073280
25 : 140661222073280
36 : 140661222073280
49 : 140661222073280
64 : 140661222073280
81 : 140661222073280
Started time consuming task thread: 140661222057536
Done with time consuming task: 140661222057536
Finished program...: 140661222073280
*/