forked from mpavezb/cpp_concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03_async.cpp
39 lines (29 loc) · 1.02 KB
/
03_async.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
#include <future>
#include <iostream>
#include <string>
void printing() {
std::cout << "printing runs on-" << std::this_thread::get_id() << std::endl;
}
int addition(int x, int y) {
std::cout << "addition runs on-" << std::this_thread::get_id() << std::endl;
return x + y;
}
int substract(int x, int y) {
std::cout << "substract runs on-" << std::this_thread::get_id() << std::endl;
return x - y;
}
int main() {
std::cout << "main thread id -" << std::this_thread::get_id() << std::endl;
int x = 100;
int y = 50;
// Runs on different thread
std::future<void> f1 = std::async(std::launch::async, printing);
// Runs deferred on the same thread
std::future<int> f2 = std::async(std::launch::deferred, addition, x, y);
// Compiler decides.
std::future<int> f3 =
std::async(std::launch::deferred | std::launch::async, substract, x, y);
f1.get();
std::cout << "value recieved using f2 future -" << f2.get() << std::endl;
std::cout << "value recieved using f2 future -" << f3.get() << std::endl;
}