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 void execute() override { 37 sum = x + y; 38 } 39 40 int x{ 0 }, y{ 0 }; 41 int& sum; 42 }; 43 44 struct fib_computation : task_emulation::base_task { 45 fib_computation(int n, int* x) : n(n), x(x) {} 46 47 void execute() override { 48 if (n < cutoff) { 49 *x = serial_fib(n); 50 } 51 else { 52 // Continuation passing 53 auto& c = *this->allocate_continuation<fib_continuation>(/* children_counter = */ 2, *x); 54 task_emulation::run_task(c.create_child<fib_computation>(n - 1, &c.x)); 55 56 // Recycling 57 this->recycle_as_child_of(c); 58 n = n - 2; 59 x = &c.y; 60 61 // Bypass is not supported by task_emulation and next_task executed directly. 62 // However, the old-TBB bypass behavior can be achieved with 63 // `return task_group::defer()` (check Migration Guide). 64 // Consider submit another task if recursion call is not acceptable 65 // i.e. instead of Recycling + Direct Body call 66 // submit task_emulation::run_task(c.create_child<fib_computation>(n - 2, &c.y)); 67 this->operator()(); 68 } 69 } 70 71 int n; 72 int* x; 73 }; 74 75 int fibonacci_two_tasks(int n) { 76 int sum{}; 77 tbb::task_group tg; 78 tg.run_and_wait( 79 task_emulation::create_root_task<fib_computation>(/* for root task = */ tg, n, &sum)); 80 return sum; 81 } 82 83 #endif // TWO_TASKS_HEADER 84