-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathasync_future_promise.cpp
More file actions
72 lines (65 loc) · 1.89 KB
/
async_future_promise.cpp
File metadata and controls
72 lines (65 loc) · 1.89 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
#include <functional>
#include <future>
#include <iostream>
int factorialSharedFuture(std::shared_future<int> f) {
int value = 1;
int n = f.get();
for (int i = 1; i <= n; i++)
value = i * value;
return value;
}
int factorialFuture(std::future<int> &f) {
int value = 1;
int n = f.get();
for (int i = 1; i <= n; i++)
value = i * value;
return value;
}
int factorial(int input) {
int value = 1;
for (int i = 1; i <= input; i++)
value = i * value;
return value;
}
int main() {
{
int input = 8;
int output;
std::future<int> future_thread = std::async(factorial, input);
output = future_thread.get();
std::cout << output << std::endl;
}
{
int input = 8;
int output;
std::future<int> future_function =
std::async(std::launch::async, factorial, input);
output = future_function.get();
std::cout << output << std::endl;
}
{
int input = 8;
int output;
std::promise<int> p;
std::future<int> inputFuture = p.get_future();
std::future<int> future_promise_factorial =
std::async(std::launch::async, factorialFuture, std::ref(inputFuture));
// some code here
p.set_value(input);
// p.set_exception(std::make_exception_ptr(std::runtime_error("Value
// couldn't be assigned")));
output = future_promise_factorial.get();
std::cout << output << std::endl;
}
{
std::promise<int> p;
std::future inputFuture = p.get_future();
std::shared_future<int> inputFutureShared = inputFuture.share();
std::future<int> future_promise_factorial1 = std::async(
std::launch::async, factorialSharedFuture, inputFutureShared);
std::future<int> future_promise_factorial2 = std::async(
std::launch::async, factorialSharedFuture, inputFutureShared);
std::future<int> future_promise_factorial3 = std::async(
std::launch::async, factorialSharedFuture, inputFutureShared);
}
}