-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync_stuff.cpp
More file actions
65 lines (46 loc) · 1.33 KB
/
async_stuff.cpp
File metadata and controls
65 lines (46 loc) · 1.33 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
/**
@author [mst]
@brief cpp multithreading basics and experiments
gains:
-basic futures/promises
@version 0.1 2023.05
*/
////////////////// LIBS
#include <iostream> // usage of console prints
#include <vector>
#include <future> // usage of futures, promises
// #include <thread>
using namespace std;
////////////////// DECL_IMPL
void product(std::promise<int> &&intPromise, int a, int b) {
intPromise.set_value(a * b);
}
struct Div {
void operator()(std::promise<int> &&intPromise, int a, int b) const
{
intPromise.set_value(a / b);
}
};
////////////////// DRIVER
int main() {
int a = 20;
int b = 10;
std::cout << std::endl;
// define the promises
std::promise<int> prodPromise;
std::promise<int> divPromise;
// get the futures
std::future<int> prodResult = prodPromise.get_future();
std::future<int> divResult = divPromise.get_future();
// calculate the result in a separate thread
std::thread prodThread(product, std::move(prodPromise), a, b);
Div div;
std::thread divThread(div, std::move(divPromise), a, b);
// get the result
std::cout << "20*10= " << prodResult.get() << std::endl;
std::cout << "20/10= " << divResult.get() << std::endl;
prodThread.join();
divThread.join();
std::cout << std::endl;
return 0;
}