C++ Library Extensions 2022.12.09
To help learn modern C++ programming
025-outcome.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
3#include <future>
4
6{
7 public:
8
9 using summation_return_t = long long;
10 using division_return_t = double;
11
13 using lock_t = std::unique_lock<mutex_t>;
14
15 static constexpr auto async = std::launch::async;
16 static constexpr auto deferred = std::launch::deferred;
17
18 private:
19
20 static inline mutex_t mutex;
21
22 public:
23
24 static
26 summation(int a, int b)
27 {
29 stream << "In summation - thread ID: " << std::this_thread::get_id();
30
31 {
32 lock_t lock(mutex);
34 }
35
37 for(int i=a; i < b; ++i)
38 s += i;
39
40 return s;
41 }
42
43 static
45 division(double p, double q)
46 {
48 stream << "In division - thread ID: " << std::this_thread::get_id();
49
50 {
51 lock_t lock(mutex);
53 }
54
55 division_return_t rlt = p / q;
56
57 if(rlt != rlt)
58 {
60
61 stream << "invalid_operation: p ="
62 << p <<", " << q;
63
65 }
66 }
67};
68
70{
71 using tis = thread_interface_space;
72
73 return tis::summation(1, max)
74 + tis::summation(1, max);
75}
76
78{
79 using tis = thread_interface_space;
80
81 try
82 {
83 std::future<tis::summation_return_t>
84 summation = std::async(tis::async, tis::summation, 1, max);
85
86 auto s = tis::summation(1, max);
87
88 return s + summation.get();
89 }
90 catch(const std::exception& e)
91 {
92 std::cerr << e.what() << '\n';
93
94 return tis::summation_return_t{};
95 }
96}
97
98int main()
99{
100 using stop_watch_t = tpf::chrono_random::stop_watch;
102
103 stop_watch_t sw;
104
105 stream <<"Single thread summation: "
106 << single_thread_summation(1'000'000'000)
107 << " - elapsed: " << sw.elapsed_time() << tpf::endl;
108
109 stream <<"Multiple thread summation: "
110 << multiple_thread_summation(1'000'000'000)
111 << " - elapsed: " << sw.elapsed_time() << tpf::endl;
112
113}
int summation(int a, int b)
std::mutex mutex
Definition: 022-mutex.cpp:12
auto multiple_thread_summation(int max)
Definition: 025-outcome.cpp:77
auto single_thread_summation(int max)
Definition: 025-outcome.cpp:69
int main()
Definition: 025-outcome.cpp:98
tpf::chrono_random::stop_watch stop_watch
auto & cout
auto & endl
tpf::sstream stream
static division_return_t division(double p, double q)
Definition: 025-outcome.cpp:45
std::unique_lock< mutex_t > lock_t
Definition: 025-outcome.cpp:13
static constexpr auto deferred
Definition: 025-outcome.cpp:16
long long summation_return_t
Definition: 025-outcome.cpp:9
static constexpr auto async
Definition: 025-outcome.cpp:15
static summation_return_t summation(int a, int b)
Definition: 025-outcome.cpp:26
std::string str() const
Definition: tpf_output.hpp:951
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