C++ Library Extensions 2022.12.09
To help learn modern C++ programming
010-thread_func.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
2#include <future>
3#include <thread>
4
5using return_t = int;
6
7return_t sum(int a, int b)
8{
10
12 stream << "Thread ID: " << std::this_thread::get_id() << " " << tpf::endl;
13
14 return a + b;
15}
16
18{
19
20 public:
21
22 return_t pro(int a, int b)
23 {
25
27 stream << "Thread ID: " << std::this_thread::get_id() << " " << tpf::endl;
28
29 return a * b;
30 }
31
32 static return_t square(int a)
33 {
34 return a * a;
35 }
36};
37
39{
40 std::future<return_t> sum_1_2 =
41 std::async( std::launch::async | std::launch::deferred, sum, 1, 2);
42
43 MyClass class_object;
44
45 std::future<return_t> pro_2_3 =
46 std::async( std::launch::async | std::launch::deferred,
47 &MyClass::pro, &class_object, 2, 3);
48
50
51 stream << "(1+2) + (2*3) = " << sum(sum_1_2.get(), pro_2_3.get()) << tpf::endl;
52}
53
55{
56
57 public:
58 int operator()(int a, int b) const
59 {
60 return a*a + b*b;
61 }
62};
63
65{
66 try
67 {
68 auto product = std::async([](auto a, auto b) { return a + b; }, // lambda taking two ints
69 2, 3 // arguments for the lambda
70 );
71
72 auto sum_closure = [](auto a, auto b) { return a + b; };
73
74 auto sum = std::async(sum_closure, 3, 4);
75
76 auto square_sum = std::async(SquareSum{}, 3, 4);
77
79
80 stream <<"product of 2 and 3 : " << product.get() << tpf::endl;
81 stream <<"sum of 3 and 4: " << sum.get() << tpf::endl;
82 stream <<"square_sum of 3 and 4: " << square_sum.get() << tpf::endl;
83 }
84 catch(const std::exception& e)
85 {
87 stream << e << tpf::endl;
88 }
89}
90int main()
91{
92 // example_for_callable_thread_functions();
94}
95
return_t sum(int a, int b)
void example_for_callable_thread_functions()
int return_t
void more_examples_for_thread_function()
int main()
tpf::sstream stream
return_t pro(int a, int b)
static return_t square(int a)
int operator()(int a, int b) const
auto product(std::vector< ElementType > const &A, std::vector< ElementType > const &B, VectorTypes... tails)
constexpr auto endl
Definition: tpf_output.hpp:973
Stream output operators << are implemented.
#define __FUNCTION_NAME__
Definition: tpf_types.hpp:88