-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc53_promise_and_future.cpp
More file actions
96 lines (84 loc) · 2.23 KB
/
c53_promise_and_future.cpp
File metadata and controls
96 lines (84 loc) · 2.23 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <chrono>
#include <future>
#include <iostream>
#include <string>
#include <thread>
/*!
* \brief std::future & std::promise
* \note A promise stores a result; a future gets the result. Together they
* create a shared state.
*
* std::future objects are usually created by std::promise, or an asynchronous
* operation.
* std::promise::set_exception() can share exceptions inter-threads.
*
* std::future assumes exclusive read access to the data, so it's used with
* single consumer thread. It is move only.
*/
void produce(std::promise<int>& promise)
{
try
{
int x{42};
std::this_thread::sleep_for(std::chrono::seconds(2));
// throw an exception under a certain condition
if (0) // or 1
{
throw std::out_of_range("Error: out of range!");
}
std::cout << "Promise sets shared state to " << x << std::endl;
promise.set_value(x);
}
catch(const std::exception& e)
{
promise.set_exception(std::current_exception());
}
}
void consume(std::future<int>& future)
{
std::cout << "Consumer getting future value...\n";
try
{
int x = future.get();
std::cout << "Consumer has got value " << x << std::endl;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
}
// a cleaner way to throw exceptions
void produce_alternative(std::promise<int>& promise)
{
int x{42};
std::this_thread::sleep_for(std::chrono::seconds(2));
if (1)
{
promise.set_exception(
std::make_exception_ptr(std::out_of_range("Out of range!")));
return;
}
std::cout << "Promise sets shared state to " << x << std::endl;
promise.set_value(x);
}
int main()
{
{
std::promise<int> prom;
std::future<int> fut = prom.get_future();
std::thread t1{produce, std::ref(prom)};
std::thread t2{consume, std::ref(fut)};
t1.join();
t2.join();
}
std::cout << std::endl;
{
std::promise<int> prom;
std::future<int> fut = prom.get_future();
std::thread t1{produce_alternative, std::ref(prom)};
std::thread t2{consume, std::ref(fut)};
t1.join();
t2.join();
}
return 0;
}