1 // The MIT License (MIT) 2 // 3 // Copyright (c) 2015 Sergey Makeev, Vadim Slyusarev 4 // 5 // Permission is hereby granted, free of charge, to any person obtaining a copy 6 // of this software and associated documentation files (the "Software"), to deal 7 // in the Software without restriction, including without limitation the rights 8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 // copies of the Software, and to permit persons to whom the Software is 10 // furnished to do so, subject to the following conditions: 11 // 12 // The above copyright notice and this permission notice shall be included in 13 // all copies or substantial portions of the Software. 14 // 15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 // THE SOFTWARE. 22 23 #pragma once 24 25 #include <MTColorTable.h> 26 #include <MTTools.h> 27 #include <MTPlatform.h> 28 #include <MTConcurrentQueueLIFO.h> 29 #include <MTStackArray.h> 30 #include <MTArrayView.h> 31 #include <MTThreadContext.h> 32 #include <MTFiberContext.h> 33 #include <MTAllocator.h> 34 #include <MTTaskPool.h> 35 36 37 namespace MT 38 { 39 40 template<typename CLASS_TYPE, typename MACRO_TYPE> 41 struct CheckType 42 { 43 static_assert(std::is_same<CLASS_TYPE, MACRO_TYPE>::value, "Invalid type in MT_DECLARE_TASK macro. See CheckType template instantiation params to details."); 44 }; 45 46 struct TypeChecker 47 { 48 template <typename T> 49 static T QueryThisType(T thisPtr) 50 { 51 return (T)nullptr; 52 } 53 }; 54 55 56 template <typename T> 57 inline void CallDtor(T * p) 58 { 59 #if _MSC_VER 60 p; 61 #endif 62 p->~T(); 63 } 64 65 } 66 67 #if _MSC_VER 68 69 // Visual Studio compile time check 70 #define COMPILE_TIME_TYPE_CHECK(TYPE) \ 71 void CompileTimeCheckMethod() \ 72 { \ 73 MT::CheckType< typename std::remove_pointer< decltype(MT::TypeChecker::QueryThisType(this)) >::type, typename TYPE > compileTypeTypesCheck; \ 74 compileTypeTypesCheck; \ 75 } 76 77 #else 78 79 // GCC, Clang and other compilers compile time check 80 #define COMPILE_TIME_TYPE_CHECK(TYPE) \ 81 void CompileTimeCheckMethod() \ 82 { \ 83 /* query this pointer type */ \ 84 typedef decltype(MT::TypeChecker::QueryThisType(this)) THIS_PTR_TYPE; \ 85 /* query class type from this pointer type */ \ 86 typedef typename std::remove_pointer<THIS_PTR_TYPE>::type CPP_TYPE; \ 87 /* define macro type */ \ 88 typedef TYPE MACRO_TYPE; \ 89 /* compile time checking that is same types */ \ 90 MT::CheckType< CPP_TYPE, MACRO_TYPE > compileTypeTypesCheck; \ 91 /* remove unused variable warning */ \ 92 compileTypeTypesCheck; \ 93 } 94 95 #endif 96 97 98 99 100 #define MT_DECLARE_TASK_IMPL(TYPE) \ 101 \ 102 COMPILE_TIME_TYPE_CHECK(TYPE) \ 103 \ 104 static void TaskEntryPoint(MT::FiberContext& fiberContext, void* userData) \ 105 { \ 106 TYPE * task = static_cast< TYPE *>(userData); \ 107 task->Do(fiberContext); \ 108 } \ 109 \ 110 static void PoolTaskDestroy(void* userData) \ 111 { \ 112 TYPE * task = static_cast< TYPE *>(userData); \ 113 MT::CallDtor( task ); \ 114 /* Find task pool header */ \ 115 MT::PoolElementHeader * poolHeader = (MT::PoolElementHeader *)((char*)userData - sizeof(MT::PoolElementHeader)); \ 116 /* Fixup pool header, mark task as unused */ \ 117 poolHeader->id.Store(MT::TaskID::UNUSED); \ 118 } \ 119 120 121 122 #ifdef MT_INSTRUMENTED_BUILD 123 #include <MTProfilerEventListener.h> 124 125 #define MT_DECLARE_TASK(TYPE, DEBUG_COLOR) \ 126 static const mt_char* GetDebugID() \ 127 { \ 128 return MT_TEXT( #TYPE ); \ 129 } \ 130 \ 131 static MT::Color::Type GetDebugColor() \ 132 { \ 133 return DEBUG_COLOR; \ 134 } \ 135 \ 136 MT_DECLARE_TASK_IMPL(TYPE); 137 138 139 #else 140 141 #define MT_DECLARE_TASK(TYPE, colorID) \ 142 MT_DECLARE_TASK_IMPL(TYPE); 143 144 #endif 145 146 147 148 149 150 151 namespace MT 152 { 153 const uint32 MT_MAX_THREAD_COUNT = 64; 154 const uint32 MT_MAX_FIBERS_COUNT = 256; 155 const uint32 MT_SCHEDULER_STACK_SIZE = 1048576; 156 const uint32 MT_FIBER_STACK_SIZE = 65536; 157 158 namespace internal 159 { 160 struct ThreadContext; 161 } 162 163 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 164 // Task scheduler 165 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 166 class TaskScheduler 167 { 168 friend class FiberContext; 169 friend struct internal::ThreadContext; 170 171 172 173 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 174 // Task group description 175 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 176 // Application can assign task group to task and later wait until group was finished. 177 class TaskGroupDescription 178 { 179 AtomicInt32 inProgressTaskCount; 180 Event allDoneEvent; 181 182 //Tasks awaiting group through FiberContext::WaitGroupAndYield call 183 ConcurrentQueueLIFO<FiberContext*> waitTasksQueue; 184 185 public: 186 187 bool debugIsFree; 188 189 190 private: 191 192 TaskGroupDescription(TaskGroupDescription& ) {} 193 void operator=(const TaskGroupDescription&) {} 194 195 public: 196 197 TaskGroupDescription() 198 { 199 inProgressTaskCount.Store(0); 200 allDoneEvent.Create( EventReset::MANUAL, true ); 201 debugIsFree = true; 202 } 203 204 int GetTaskCount() const 205 { 206 return inProgressTaskCount.Load(); 207 } 208 209 ConcurrentQueueLIFO<FiberContext*> & GetWaitQueue() 210 { 211 return waitTasksQueue; 212 } 213 214 int Dec() 215 { 216 return inProgressTaskCount.DecFetch(); 217 } 218 219 int Inc() 220 { 221 return inProgressTaskCount.IncFetch(); 222 } 223 224 int Add(int sum) 225 { 226 return inProgressTaskCount.AddFetch(sum); 227 } 228 229 void Signal() 230 { 231 allDoneEvent.Signal(); 232 } 233 234 void Reset() 235 { 236 allDoneEvent.Reset(); 237 } 238 239 bool Wait(uint32 milliseconds) 240 { 241 return allDoneEvent.Wait(milliseconds); 242 } 243 }; 244 245 246 // Thread index for new task 247 AtomicInt32 roundRobinThreadIndex; 248 249 // Started threads count 250 AtomicInt32 startedThreadsCount; 251 252 // Threads created by task manager 253 volatile uint32 threadsCount; 254 internal::ThreadContext threadContext[MT_MAX_THREAD_COUNT]; 255 256 // All groups task statistic 257 TaskGroupDescription allGroups; 258 259 // Groups pool 260 ConcurrentQueueLIFO<TaskGroup> availableGroups; 261 262 // 263 TaskGroupDescription groupStats[TaskGroup::MT_MAX_GROUPS_COUNT]; 264 265 // Fibers pool 266 ConcurrentQueueLIFO<FiberContext*> availableFibers; 267 268 // Fibers context 269 FiberContext fiberContext[MT_MAX_FIBERS_COUNT]; 270 271 #ifdef MT_INSTRUMENTED_BUILD 272 IProfilerEventListener * profilerEventListener; 273 #endif 274 275 FiberContext* RequestFiberContext(internal::GroupedTask& task); 276 void ReleaseFiberContext(FiberContext* fiberExecutionContext); 277 void RunTasksImpl(ArrayView<internal::TaskBucket>& buckets, FiberContext * parentFiber, bool restoredFromAwaitState); 278 TaskGroupDescription & GetGroupDesc(TaskGroup group); 279 280 static void ThreadMain( void* userData ); 281 static void FiberMain( void* userData ); 282 static bool TryStealTask(internal::ThreadContext& threadContext, internal::GroupedTask & task, uint32 workersCount); 283 284 static FiberContext* ExecuteTask (internal::ThreadContext& threadContext, FiberContext* fiberContext); 285 286 public: 287 288 /// \brief Initializes a new instance of the TaskScheduler class. 289 /// \param workerThreadsCount Worker threads count. Automatically determines the required number of threads if workerThreadsCount set to 0 290 #ifdef MT_INSTRUMENTED_BUILD 291 TaskScheduler(uint32 workerThreadsCount = 0, IProfilerEventListener* listener = nullptr); 292 #else 293 TaskScheduler(uint32 workerThreadsCount = 0); 294 #endif 295 296 297 ~TaskScheduler(); 298 299 template<class TTask> 300 void RunAsync(TaskGroup group, TTask* taskArray, uint32 taskCount); 301 302 void RunAsync(TaskGroup group, TaskHandle* taskHandleArray, uint32 taskHandleCount); 303 304 305 bool WaitGroup(TaskGroup group, uint32 milliseconds); 306 bool WaitAll(uint32 milliseconds); 307 308 TaskGroup CreateGroup(); 309 void ReleaseGroup(TaskGroup group); 310 311 bool IsEmpty(); 312 313 uint32 GetWorkerCount() const; 314 315 bool IsWorkerThread() const; 316 317 #ifdef MT_INSTRUMENTED_BUILD 318 319 inline IProfilerEventListener* GetProfilerEventListener() 320 { 321 return profilerEventListener; 322 } 323 324 #endif 325 }; 326 } 327 328 #include "MTScheduler.inl" 329 #include "MTFiberContext.inl" 330