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 <MTConfig.h> 26 #include <MTColorTable.h> 27 #include <MTTools.h> 28 #include <MTPlatform.h> 29 #include <MTConcurrentQueueLIFO.h> 30 #include <MTStackArray.h> 31 #include <MTArrayView.h> 32 #include <MTThreadContext.h> 33 #include <MTFiberContext.h> 34 #include <MTAppInterop.h> 35 #include <MTTaskPool.h> 36 #include <MTStackRequirements.h> 37 #include <Scopes/MTScopes.h> 38 39 40 namespace MT 41 { 42 43 template<typename CLASS_TYPE, typename MACRO_TYPE> 44 struct CheckType 45 { 46 static_assert(std::is_same<CLASS_TYPE, MACRO_TYPE>::value, "Invalid type in MT_DECLARE_TASK macro. See CheckType template instantiation params to details."); 47 }; 48 49 struct TypeChecker 50 { 51 template <typename T> 52 static T QueryThisType(T thisPtr) 53 { 54 MT_UNUSED(thisPtr); 55 return (T)nullptr; 56 } 57 }; 58 59 60 template <typename T> 61 inline void CallDtor(T* p) 62 { 63 MT_UNUSED(p); 64 p->~T(); 65 } 66 67 } 68 69 #if MT_MSVC_COMPILER_FAMILY 70 71 // Visual Studio compile time check 72 #define MT_COMPILE_TIME_TYPE_CHECK(TYPE) \ 73 void CompileTimeCheckMethod() \ 74 { \ 75 MT::CheckType< typename std::remove_pointer< decltype(MT::TypeChecker::QueryThisType(this)) >::type, typename TYPE > compileTypeTypesCheck; \ 76 compileTypeTypesCheck; \ 77 } 78 79 #elif MT_GCC_COMPILER_FAMILY 80 81 // GCC, Clang and other compilers compile time check 82 #define MT_COMPILE_TIME_TYPE_CHECK(TYPE) \ 83 void CompileTimeCheckMethod() \ 84 { \ 85 /* query this pointer type */ \ 86 typedef decltype(MT::TypeChecker::QueryThisType(this)) THIS_PTR_TYPE; \ 87 /* query class type from this pointer type */ \ 88 typedef typename std::remove_pointer<THIS_PTR_TYPE>::type CPP_TYPE; \ 89 /* define macro type */ \ 90 typedef TYPE MACRO_TYPE; \ 91 /* compile time checking that is same types */ \ 92 MT::CheckType< CPP_TYPE, MACRO_TYPE > compileTypeTypesCheck; \ 93 /* remove unused variable warning */ \ 94 MT_UNUSED(compileTypeTypesCheck); \ 95 } 96 97 #else 98 99 #error Platform is not supported. 100 101 #endif 102 103 104 105 106 #define MT_DECLARE_TASK_IMPL(TYPE, STACK_REQUIREMENTS) \ 107 \ 108 MT_COMPILE_TIME_TYPE_CHECK(TYPE) \ 109 \ 110 static void TaskEntryPoint(MT::FiberContext& fiberContext, const void* userData) \ 111 { \ 112 /* C style cast */ \ 113 TYPE * task = (TYPE *)(userData); \ 114 task->Do(fiberContext); \ 115 } \ 116 \ 117 static void PoolTaskDestroy(const void* userData) \ 118 { \ 119 /* C style cast */ \ 120 TYPE * task = (TYPE *)(userData); \ 121 MT::CallDtor( task ); \ 122 /* Find task pool header */ \ 123 MT::PoolElementHeader * poolHeader = (MT::PoolElementHeader *)((char*)userData - sizeof(MT::PoolElementHeader)); \ 124 /* Fixup pool header, mark task as unused */ \ 125 poolHeader->id.Store(MT::TaskID::UNUSED); \ 126 } \ 127 \ 128 static MT::StackRequirements::Type GetStackRequirements() \ 129 { \ 130 return STACK_REQUIREMENTS; \ 131 } \ 132 133 134 135 #ifdef MT_INSTRUMENTED_BUILD 136 #include <MTProfilerEventListener.h> 137 138 #define MT_DECLARE_TASK(TYPE, STACK_REQUIREMENTS, DEBUG_COLOR) \ 139 static const mt_char* GetDebugID() \ 140 { \ 141 return MT_TEXT( #TYPE ); \ 142 } \ 143 \ 144 static MT::Color::Type GetDebugColor() \ 145 { \ 146 return DEBUG_COLOR; \ 147 } \ 148 \ 149 MT_DECLARE_TASK_IMPL(TYPE, STACK_REQUIREMENTS); 150 151 152 #else 153 154 #define MT_DECLARE_TASK(TYPE, STACK_REQUIREMENTS, DEBUG_COLOR) \ 155 MT_DECLARE_TASK_IMPL(TYPE, STACK_REQUIREMENTS); 156 157 #endif 158 159 160 161 162 #if defined(MT_DEBUG) || defined(MT_INSTRUMENTED_BUILD) 163 #define MT_GROUP_DEBUG (1) 164 #endif 165 166 167 168 namespace MT 169 { 170 const uint32 MT_MAX_THREAD_COUNT = 64; 171 const uint32 MT_SCHEDULER_STACK_SIZE = 1048576; // 1Mb 172 173 const uint32 MT_MAX_STANDART_FIBERS_COUNT = 256; 174 const uint32 MT_STANDART_FIBER_STACK_SIZE = 32768; //32Kb 175 176 const uint32 MT_MAX_EXTENDED_FIBERS_COUNT = 8; 177 const uint32 MT_EXTENDED_FIBER_STACK_SIZE = 1048576; // 1Mb 178 179 namespace internal 180 { 181 struct ThreadContext; 182 } 183 184 struct WorkerThreadParams 185 { 186 uint32 core; 187 ThreadPriority::Type priority; 188 189 WorkerThreadParams() 190 : core(MT_CPUCORE_ANY) 191 , priority(ThreadPriority::DEFAULT) 192 { 193 } 194 }; 195 196 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 197 // Task scheduler 198 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 199 class TaskScheduler 200 { 201 friend class FiberContext; 202 friend struct internal::ThreadContext; 203 204 205 206 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 207 // Task group description 208 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 209 // Application can assign task group to task and later wait until group was finished. 210 class TaskGroupDescription 211 { 212 Atomic32<int32> inProgressTaskCount; 213 Event allDoneEvent; 214 215 #if MT_GROUP_DEBUG 216 bool debugIsFree; 217 #endif 218 219 public: 220 221 MT_NOCOPYABLE(TaskGroupDescription); 222 223 TaskGroupDescription() 224 { 225 inProgressTaskCount.Store(0); 226 allDoneEvent.Create( EventReset::MANUAL, true ); 227 228 #if MT_GROUP_DEBUG 229 debugIsFree = true; 230 #endif 231 } 232 233 int GetTaskCount() const 234 { 235 return inProgressTaskCount.Load(); 236 } 237 238 int Dec() 239 { 240 return inProgressTaskCount.DecFetch(); 241 } 242 243 int Inc() 244 { 245 return inProgressTaskCount.IncFetch(); 246 } 247 248 int Add(int sum) 249 { 250 return inProgressTaskCount.AddFetch(sum); 251 } 252 253 void Signal() 254 { 255 allDoneEvent.Signal(); 256 } 257 258 void Reset() 259 { 260 allDoneEvent.Reset(); 261 } 262 263 bool Wait(uint32 milliseconds) 264 { 265 return allDoneEvent.Wait(milliseconds); 266 } 267 268 #if MT_GROUP_DEBUG 269 void SetDebugIsFree(bool _debugIsFree) 270 { 271 debugIsFree = _debugIsFree; 272 } 273 274 bool GetDebugIsFree() const 275 { 276 return debugIsFree; 277 } 278 #endif 279 }; 280 281 282 // Thread index for new task 283 Atomic32<int32> roundRobinThreadIndex; 284 285 // Started threads count 286 Atomic32<int32> startedThreadsCount; 287 288 // Threads created by task manager 289 Atomic32<int32> threadsCount; 290 internal::ThreadContext threadContext[MT_MAX_THREAD_COUNT]; 291 292 // All groups task statistic 293 TaskGroupDescription allGroups; 294 295 // Groups pool 296 ConcurrentQueueLIFO<TaskGroup> availableGroups; 297 298 // 299 TaskGroupDescription groupStats[TaskGroup::MT_MAX_GROUPS_COUNT]; 300 301 // Fibers context 302 FiberContext standartFiberContexts[MT_MAX_STANDART_FIBERS_COUNT]; 303 FiberContext extendedFiberContexts[MT_MAX_EXTENDED_FIBERS_COUNT]; 304 305 // Fibers pool 306 ConcurrentQueueLIFO<FiberContext*> standartFibersAvailable; 307 ConcurrentQueueLIFO<FiberContext*> extendedFibersAvailable; 308 309 ConcurrentQueueLIFO<FiberContext*>* GetFibersStorage(MT::StackRequirements::Type stackRequirements); 310 311 #ifdef MT_INSTRUMENTED_BUILD 312 IProfilerEventListener * profilerEventListener; 313 #endif 314 315 FiberContext* RequestFiberContext(internal::GroupedTask& task); 316 void ReleaseFiberContext(FiberContext* fiberExecutionContext); 317 void RunTasksImpl(ArrayView<internal::TaskBucket>& buckets, FiberContext * parentFiber, bool restoredFromAwaitState); 318 TaskGroupDescription & GetGroupDesc(TaskGroup group); 319 320 static void WorkerThreadMain( void* userData ); 321 static void SchedulerFiberMain( void* userData ); 322 static void FiberMain( void* userData ); 323 static bool TryStealTask(internal::ThreadContext& threadContext, internal::GroupedTask & task, uint32 workersCount); 324 325 static FiberContext* ExecuteTask (internal::ThreadContext& threadContext, FiberContext* fiberContext); 326 327 public: 328 329 /// \brief Initializes a new instance of the TaskScheduler class. 330 /// \param workerThreadsCount Worker threads count. Automatically determines the required number of threads if workerThreadsCount set to 0 331 #ifdef MT_INSTRUMENTED_BUILD 332 TaskScheduler(uint32 workerThreadsCount = 0, WorkerThreadParams* workerParameters = nullptr, IProfilerEventListener* listener = nullptr); 333 #else 334 TaskScheduler(uint32 workerThreadsCount = 0, WorkerThreadParams* workerParameters = nullptr); 335 #endif 336 337 338 ~TaskScheduler(); 339 340 template<class TTask> 341 void RunAsync(TaskGroup group, const TTask* taskArray, uint32 taskCount); 342 343 void RunAsync(TaskGroup group, const TaskHandle* taskHandleArray, uint32 taskHandleCount); 344 345 /// \brief Wait while no more tasks in specific group. 346 /// \return true - if no more tasks in specific group. false - if timeout in milliseconds has reached and group still has some tasks. 347 bool WaitGroup(TaskGroup group, uint32 milliseconds); 348 349 bool WaitAll(uint32 milliseconds); 350 351 TaskGroup CreateGroup(); 352 void ReleaseGroup(TaskGroup group); 353 354 bool IsEmpty(); 355 356 int32 GetWorkersCount() const; 357 358 bool IsWorkerThread() const; 359 360 #ifdef MT_INSTRUMENTED_BUILD 361 362 inline IProfilerEventListener* GetProfilerEventListener() 363 { 364 return profilerEventListener; 365 } 366 367 #endif 368 }; 369 } 370 371 #include "MTScheduler.inl" 372 #include "MTFiberContext.inl" 373