Games Task Scheduler (GTS)
A multi-processor scheduling framework for games engines
2_blocking_join.h
1 /*******************************************************************************
2  * Copyright 2019 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a copy
5  * of this software and associated documentation files(the "Software"), to deal
6  * in the Software without restriction, including without limitation the rights
7  * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
8  * copies of the Software, and to permit persons to whom the Software is
9  * furnished to do so, subject to the following conditions :
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
17  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20  * THE SOFTWARE.
21  ******************************************************************************/
22 #pragma once
23 
24 #include <cassert>
25 #include <iostream>
26 #include <chrono>
27 
28 #include <gts/micro_scheduler/WorkerPool.h>
29 #include <gts/micro_scheduler/MicroScheduler.h>
30 
31 using namespace gts;
32 
33 namespace gts_examples {
34 
35 //------------------------------------------------------------------------------
36 // A parallel Fibonacci number calculator. NOTE: this is a terrible way to calculate
37 // a Fibonacci number, however it is a simple way to demonstrate the fork-join
38 // model of the micro-scheduler.
39 struct ParallelFibTask1 : public Task
40 {
41  uint32_t fibN;
42  uint64_t* sum;
43 
45  uint32_t fibN,
46  uint64_t* sum)
47  : fibN(fibN)
48  , sum(sum) {}
49 
50  virtual Task* execute(gts::TaskContext const& ctx) override
51  {
52  // Recursively fork tasks until the base case is reached, then join
53  // the task sums to produce the Fibonacci number.
54 
55  if (fibN <= 2)
56  {
57  *sum = 1;
58  }
59  else
60  {
61  // We are going to fork 2 new tasks, one for f(n-1) and one for
62  // f(n-2), so we need to add them as reference to this task. We
63  // are also going to call waitForAll(), which require another
64  // reference. If we forget to add these reference, this task will
65  // exit and be destroyed leaving the new children dangling.
66  addRef(3, gts::memory_order::relaxed);
67  // Doing this in bulk up front also let's us avoid the expensive
68  // cache synchronization of XADD per added child.
69 
70  // NOTE: There is a Task::addChildTaskWithRef function that will
71  // add a ref per child, but it is not recommended due to the atomic
72  // increment cost. Further it could cause subtle race conditions
73  // with continuation passing (next lesson).
74 
75  // Fork f(n-1):
76 
77  // Create and init the task
78  uint64_t sumLeft;
79  Task* pLeftChild = ctx.pMicroScheduler->allocateTask<ParallelFibTask1>(fibN - 1, &sumLeft);
80  // Add the task as a child of this task.
81  addChildTaskWithoutRef(pLeftChild);
82  // Queue it for execution.
83  ctx.pMicroScheduler->spawnTask(pLeftChild);
84 
85  // Fork f(n-2):
86 
87  // Create and init the task
88  uint64_t sumRight;
89  Task* pRightChild = ctx.pMicroScheduler->allocateTask<ParallelFibTask1>(fibN - 2, &sumRight);
90  // Add the task as a child of this task.
91  addChildTaskWithoutRef(pRightChild);
92  // Queue it for execution.
93  ctx.pMicroScheduler->spawnTask(pRightChild);
94 
95  // Wait for the forked children to finish, i.e. join.
96  // NOTE: While this is a simple way to join, it has a latency
97  // problem. Since wait will execute other tasks until the children
98  // are complete, the child may complete well before this thread
99  // finishes helping with other tasks.
100  waitForAll();
101 
102  // Calculate the fib number for this task.
103  *sum = sumLeft + sumRight;
104  }
105 
106  return nullptr;
107  }
108 };
109 
110 //------------------------------------------------------------------------------
111 void blockingJoin(uint32_t fibN)
112 {
113  printf ("================\n");
114  printf ("blockingJoin\n");
115  printf ("================\n");
116 
117  // Init boilerplate
118  WorkerPool workerPool;
119  bool result = workerPool.initialize();
120  GTS_ASSERT(result);
121  MicroScheduler microScheduler;
122  result = microScheduler.initialize(&workerPool);
123  GTS_ASSERT(result);
124 
125  uint64_t fibVal = 0;
126 
127  auto start = std::chrono::high_resolution_clock::now();
128 
129  // Create the fib task.
130  Task* pTask = microScheduler.allocateTask<ParallelFibTask1>(fibN, &fibVal);
131 
132  // Queue and wait for the task to complete.
133  microScheduler.spawnTaskAndWait(pTask);
134  // NOTE: wait ^^^^ does NOT mean that this thread is idle. This thread will
135  // actively execute any tasks in the scheduler until pTask completes.
136 
137  auto end = std::chrono::high_resolution_clock::now();
138 
139  std::cout << "Fib " << fibN << " is: " << fibVal << std::endl;
140  std::cout << "Time (ms): " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << std::endl;
141 
142  microScheduler.shutdown();
143  workerPool.shutdown();
144 }
145 
146 } // namespace gts_examples
A work-stealing task scheduler. The scheduler is executed by the WorkerPool it is initialized with.
Definition: MicroScheduler.h:81
void spawnTaskAndWait(Task *pTask, uint32_t priority=0)
Spawns the specified 'pTask' to be executed by the scheduler and then waits for its reference count t...
void spawnTask(Task *pTask, uint32_t priority=0)
Spawns the specified 'pTask' to be executed by the scheduler. Spawned tasks are executed in LIFO orde...
bool initialize(WorkerPool *pWorkerPool)
Initializes the MicroScheduler and attaches it to pWorkPool, where each worker in pWorkPool will exec...
void shutdown()
Stops the MicroScheduler and destroys all resources. The TaskSchuduler is now in an unusable state....
GTS_INLINE TTask * allocateTask(TArgs &&... args)
Allocates a new Task object of type TTask.
Definition: MicroScheduler.h:145
A Task payload that embeds TFunc and TArgs into the Task's data. It makes it easy to construct a Task...
Definition: Task.h:120
A collection of running Worker threads that a MicroScheduler can be run on.
Definition: WorkerPool.h:54
bool initialize(uint32_t threadCount=0)
#define GTS_ASSERT(expr)
Causes execution to break when expr is false.
Definition: Assert.h:144
The context associated with the task being executed.
Definition: MicroSchedulerTypes.h:54
MicroScheduler * pMicroScheduler
The MicroScheduler executing the Task.
Definition: MicroSchedulerTypes.h:59
Definition: 2_blocking_join.h:40