C++ Library Extensions 2022.12.09
To help learn modern C++ programming
052-tbb.cpp
Go to the documentation of this file.
1#include <iostream>
2#include <mutex>
3#include <tbb/tbb.h>
4#include <tbb/concurrent_vector.h>
5
6
7void test_tbb()
8{
9 tbb::task_scheduler_init init;
10
12 tbb::parallel_for(1, 10, [&mutex](auto& i)
13 {
14 std::lock_guard<std::mutex> lock(mutex);
15 std::cout << i << std::endl;
16 } );
17}
18
19template<typename Type>
21{
22 if (n < 2) // n = 0 or 1
23 return n;
24 else
26}
27
28template<typename Type>
30{
31 if(n < 2)
32 return n;
33 else
34 {
35 Type fn_2 = 0;
36 Type fn_1 = 1;
37 Type fn;
38
39 for(Type i=2; i <= n; ++i)
40 {
41 fn = fn_2 + fn_1;
42 fn_2 = fn_1; fn_1 = fn;
43 }
44
45 return fn;
46 }
47
48}
49
51{
52 for(int i=0; i < 10; ++i)
54}
55
57{
58 int fn_2 = 0;
59 int fn_1 = 1;
60 int fn;
61
62 auto fibonacci = [&fn_2, &fn_1, &fn]()
63 {
64 fn = fn_2 + fn_1;
65
66 fn_2 = fn_1; fn_1 = fn;
67
68 return fn;
69 };
70
71 std::cout << fn_2 << std::endl;
72 std::cout << fn_1 << std::endl;
73
74 for(int i=0; i < 10; ++i)
75 {
77 }
78
79}
80
81const int CutOff = 16;
82class FibTask: public tbb::task
83{
84 private:
85 const long m_n;
86 long* const m_sum;
87
88 using base = tbb::task;
89
90 public:
91 FibTask(long n, long* sum): m_n{n}, m_sum{sum} { }
92
93 tbb::task* execute() override
94 {
95 if(m_n < CutOff)
96 {
97 *m_sum = serial_fibonacci_recursion(m_n);
98 }
99 else
100 {
101 long x, y;
102 FibTask& a = *new(base::allocate_child()) FibTask(m_n-1, &x);
103 FibTask& b = *new(base::allocate_child()) FibTask(m_n-2, &y);
104
105 base::set_ref_count(3);
106 base::spawn(b);
107 base::spawn_and_wait_for_all(a);
108
109 *m_sum = x + y;
110 }
111
112 return nullptr;
113 }
114};
115
116long ParallelFib(long n)
117{
118 long sum;
119 FibTask& a = *new(tbb::task::allocate_root()) FibTask(n, &sum);
120
121 tbb::task::spawn_root_and_wait(a);
122
123 return sum;
124}
125/*
126
127 (n, r) = (n-1, r-1) + (n-1, r)
128
129 (4, 2) = (3, 1) + (3, 2)
130
131 */
132
134{
135 for(long i=0; i < 10l; ++i)
137}
138
139int main()
140{
141 // test_tbb();
142
143 // test_serial_fibonacci();
144 // test_fibonacci_lambda();
145
147}
return_t sum(int a, int b)
std::mutex mutex
Definition: 022-mutex.cpp:12
auto & cout
bool parallel_for(CallbackType &&callback, PolicyType &&policy, BeginType begin_index, EndType end_index)
const int CutOff
Definition: 052-tbb.cpp:81
long ParallelFib(long n)
Definition: 052-tbb.cpp:116
void test_tbb()
Definition: 052-tbb.cpp:7
Type serial_fibonacci_recursion(Type n)
Definition: 052-tbb.cpp:20
void test_parallel_fibonacci()
Definition: 052-tbb.cpp:133
void test_fibonacci_lambda()
Definition: 052-tbb.cpp:56
void test_serial_fibonacci()
Definition: 052-tbb.cpp:50
Type serial_fibonacci_loop(Type n)
Definition: 052-tbb.cpp:29
int main()
Definition: 052-tbb.cpp:139
auto & endl
tbb::task * execute() override
Definition: 052-tbb.cpp:93
FibTask(long n, long *sum)
Definition: 052-tbb.cpp:91