-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathpromiseFuture.cpp
49 lines (33 loc) · 969 Bytes
/
promiseFuture.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
#include <future>
#include <iostream>
#include <thread>
#include <utility>
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);
}
};
int main(){
int a = 20;
int b = 10;
std::cout << '\n';
// 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 separat 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() << '\n';
std::cout << "20 / 10 = " << divResult.get() << '\n';
prodThread.join();
divThread.join();
std::cout << '\n';
}