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 TWO_TASKS_HEADER 18 #define TWO_TASKS_HEADER 19 20 #include "task_emulation_layer.h" 21 22 #include <iostream> 23 #include <numeric> 24 #include <utility> 25 #include <functional> 26 27 extern int cutoff; 28 29 long serial_fib(int n) { 30 return n < 2 ? n : serial_fib(n - 1) + serial_fib(n - 2); 31 } 32 33 struct fib_continuation : task_emulation::base_task { 34 fib_continuation(int& s) : sum(s) {} 35 36 task_emulation::base_task* execute() override { 37 sum = x + y; 38 return nullptr; 39 } 40 41 int x{ 0 }, y{ 0 }; 42 int& sum; 43 }; 44 45 struct fib_computation : task_emulation::base_task { 46 fib_computation(int n, int* x) : n(n), x(x) {} 47 48 task_emulation::base_task* execute() override { 49 task_emulation::base_task* bypass = nullptr; 50 if (n < cutoff) { 51 *x = serial_fib(n); 52 } 53 else { 54 // Continuation passing 55 auto& c = *this->allocate_continuation<fib_continuation>(/* children_counter = */ 2, *x); 56 task_emulation::run_task(c.create_child<fib_computation>(n - 1, &c.x)); 57 58 // Recycling 59 this->recycle_as_child_of(c); 60 n = n - 2; 61 x = &c.y; 62 bypass = this; 63 } 64 return bypass; 65 } 66 67 int n; 68 int* x; 69 }; 70 71 int fibonacci_two_tasks(int n) { 72 int sum{}; 73 tbb::task_group tg; 74 tg.run_and_wait( 75 task_emulation::create_root_task<fib_computation>(/* for root task = */ tg, n, &sum)); 76 return sum; 77 } 78 79 #endif // TWO_TASKS_HEADER 80