1 /* 2 Copyright (c) 2023 Intel Corporation 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 #ifndef SINGLE_TASK_HEADER 18 #define SINGLE_TASK_HEADER 19 20 #include "task_emulation_layer.h" 21 22 #include <iostream> 23 #include <numeric> 24 #include <utility> 25 26 extern int cutoff; 27 extern bool testing_enabled; 28 29 long serial_fib_1(int n) { 30 return n < 2 ? n : serial_fib_1(n - 1) + serial_fib_1(n - 2); 31 } 32 33 struct single_fib_task : task_emulation::base_task { 34 enum class state { 35 compute, 36 sum 37 }; 38 39 single_fib_task(int n, int* x) : n(n), x(x), s(state::compute) 40 {} 41 42 task_emulation::base_task* execute() override { 43 task_emulation::base_task* bypass = nullptr; 44 switch (s) { 45 case state::compute : { 46 bypass = compute_impl(); 47 break; 48 } 49 case state::sum : { 50 *x = x_l + x_r; 51 52 if (testing_enabled) { 53 if (n == cutoff && num_recycles > 0) { 54 --num_recycles; 55 bypass = compute_impl(); 56 } 57 } 58 59 break; 60 } 61 } 62 return bypass; 63 } 64 65 task_emulation::base_task* compute_impl() { 66 task_emulation::base_task* bypass = nullptr; 67 if (n < cutoff) { 68 *x = serial_fib_1(n); 69 } 70 else { 71 bypass = this->allocate_child_and_increment<single_fib_task>(n - 2, &x_r); 72 task_emulation::run_task(this->allocate_child_and_increment<single_fib_task>(n - 1, &x_l)); 73 74 // Recycling 75 this->s = state::sum; 76 this->recycle_as_continuation(); 77 } 78 return bypass; 79 } 80 81 82 int n; 83 int* x; 84 state s; 85 86 int x_l{ 0 }, x_r{ 0 }; 87 int num_recycles{5}; 88 }; 89 90 int fibonacci_single_task(int n) { 91 int sum{}; 92 tbb::task_group tg; 93 task_emulation::run_and_wait(tg, task_emulation::allocate_root_task<single_fib_task>(/* for root task = */ tg, n, &sum)); 94 return sum; 95 } 96 97 #endif // SINGLE_TASK_HEADER 98