C++ Library Extensions 2022.12.09
To help learn modern C++ programming
019-promise_future.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
2
5
6// thread function
7void division(std::promise<int>& promise, int a, int b)
8{
9 try
10 {
11 if(b == 0)
12 {
13 Tpf_ThrowDebugException("Division By Zero");
14 }
15 else
16 {
17 // this is return value of division()
18 promise.set_value(a / b);
19 }
20 }
21 catch(...)
22 {
23 promise.set_exception( std::current_exception() );
24 }
25}
26
27/*
28 This is the canonical use of std::promise, std::future, std::thread.
29
30 The C++2a Standard will introduce coroutine, which is based on
31 std::promise, std::future, std::thread.
32
33 If you have concrete understanding of these things now,
34 you are prepared for your future.
35
36 Also, std::async, std::packaged_task are also
37 implemented using std::promise, std::future, std::thread.
38
39 Without having solid understanding of these fundamentals,
40 all your efforts for C++ Multithreading will turn out in vain.
41*/
43{
44 using return_t = int;
45
46 // by declaring an instance of promise,
47 // this promise dynamically allocates memory on free-store,
48 // this memory is shared among different threads.
49 // this memory is called "shared state"
50 std::promise<return_t> promise;
51
52 // promise.get_future() returns an instance of future<return_t>,
53 // which has pointer to the shared memory dynamically allocated by std::promise<return_t>
54 // so, std::promise<return_t> and std::future<return_t> share "shared state"
55 // std::future<return_t> future = promise.get_future();
56 auto future = promise.get_future();
57
58 // we create a thread that runs immediately.
59 std::thread t { division, std::ref(promise), 8, 2};
60
61 t.detach(); // by detaching an instance of std::thread,
62 // the thread function, division() runs in the background thread.
63
64 std::promise<return_t> failed_promise;
65 auto failed_future = failed_promise.get_future();
66
67 std::thread failed_thread { division, std::ref(failed_promise), 8, 0};
68 failed_thread.detach(); // now the thread runs in the background
69
70 try
71 {
72 stream << "8 / 2 = " << future.get() << endl;
73
74 stream << "8 / 0 = " << failed_future.get() << endl;
75 }
76 catch(const std::exception& e)
77 {
78 stream << e << endl;
79 }
80
81}
82
83int main()
84{
86}
int return_t
reference_wrapper< Type > ref(Type &val) noexcept
tpf::sstream stream
void division(std::promise< int > &promise, int a, int b)
void examples_for_promise_future()
auto endl
int main()
constexpr auto endl
Definition: tpf_output.hpp:973
Stream output operators << are implemented.
#define Tpf_ThrowDebugException(debug_message)
Throw a debug_exception with message as argument.
Definition: tpf_types.hpp:1416