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 
28 long serial_fib_1(int n) {
29     return n < 2 ? n : serial_fib_1(n - 1) + serial_fib_1(n - 2);
30 }
31 
32 struct single_fib_task : task_emulation::base_task {
33     enum class state {
34         compute,
35         sum
36     };
37 
38     single_fib_task(int n, int* x) : n(n), x(x), s(state::compute)
39     {}
40 
41     void execute() override {
42         switch (s) {
43             case state::compute : {
44                 compute_impl();
45                 break;
46             }
47             case state::sum : {
48                 *x = x_l + x_r;
49                 break;
50             }
51         }
52     }
53 
54     void compute_impl() {
55         if (n < cutoff) {
56             *x = serial_fib_1(n);
57         }
58         else {
59             auto bypass = this->allocate_child_and_increment<single_fib_task>(n - 2, &x_r);
60             task_emulation::run_task(this->allocate_child_and_increment<single_fib_task>(n - 1, &x_l));
61 
62             // Recycling
63             this->s = state::sum;
64             this->recycle_as_continuation();
65 
66             // Bypass is not supported by task_emulation and next_task executed directly.
67             // However, the old-TBB bypass behavior can be achieved with
68             // `return task_group::defer()` (check Migration Guide).
69             // Consider submit another task if recursion call is not acceptable
70             // i.e. instead of Direct Body call
71             // submit task_emulation::run_task(this->allocate_child_and_increment<single_fib_task>(n - 2, &x_r));
72             bypass->operator()();
73         }
74     }
75 
76 
77     int n;
78     int* x;
79     state s;
80 
81     int x_l{ 0 }, x_r{ 0 };
82 };
83 
84 int fibonacci_single_task(int n) {
85     int sum{};
86     tbb::task_group tg;
87     task_emulation::run_and_wait(tg, task_emulation::allocate_root_task<single_fib_task>(/* for root task = */ tg, n, &sum));
88     return sum;
89 }
90 
91 #endif // SINGLE_TASK_HEADER
92