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 #include <MTScheduler.h>
24 #include <string.h> // for memset
25 
26 namespace MT
27 {
28 
29 #ifdef MT_INSTRUMENTED_BUILD
30 	TaskScheduler::TaskScheduler(uint32 workerThreadsCount, IProfilerEventListener* listener)
31 #else
32 	TaskScheduler::TaskScheduler(uint32 workerThreadsCount)
33 #endif
34 		: roundRobinThreadIndex(0)
35 		, startedThreadsCount(0)
36 	{
37 
38 #ifdef MT_INSTRUMENTED_BUILD
39 		profilerEventListener = listener;
40 #endif
41 
42 		if (workerThreadsCount != 0)
43 		{
44 			threadsCount.StoreRelaxed( MT::Clamp(workerThreadsCount, (uint32)1, (uint32)MT_MAX_THREAD_COUNT) );
45 		} else
46 		{
47 			//query number of processor
48 			threadsCount.StoreRelaxed( (uint32)MT::Clamp(Thread::GetNumberOfHardwareThreads(), 1, (int)MT_MAX_THREAD_COUNT) );
49 		}
50 
51 		// create fiber pool (fibers with standard stack size)
52 		for (uint32 i = 0; i < MT_MAX_STANDART_FIBERS_COUNT; i++)
53 		{
54 			FiberContext& context = standartFiberContexts[i];
55 			context.fiber.Create(MT_STANDART_FIBER_STACK_SIZE, FiberMain, &context);
56 			standartFibersAvailable.Push( &context );
57 		}
58 
59 		// create fiber pool (fibers with extended stack size)
60 		for (uint32 i = 0; i < MT_MAX_EXTENDED_FIBERS_COUNT; i++)
61 		{
62 			FiberContext& context = extendedFiberContexts[i];
63 			context.fiber.Create(MT_EXTENDED_FIBER_STACK_SIZE, FiberMain, &context);
64 			extendedFibersAvailable.Push( &context );
65 		}
66 
67 
68 		for (int16 i = 0; i < TaskGroup::MT_MAX_GROUPS_COUNT; i++)
69 		{
70 			if (i != TaskGroup::DEFAULT)
71 			{
72 				availableGroups.Push( TaskGroup(i) );
73 			}
74 		}
75 
76 		groupStats[TaskGroup::DEFAULT].SetDebugIsFree(false);
77 
78 		// create worker thread pool
79 		int32 totalThreadsCount = GetWorkersCount();
80 		for (int32 i = 0; i < totalThreadsCount; i++)
81 		{
82 			threadContext[i].SetThreadIndex(i);
83 			threadContext[i].taskScheduler = this;
84 			threadContext[i].thread.Start( MT_SCHEDULER_STACK_SIZE, ThreadMain, &threadContext[i] );
85 		}
86 	}
87 
88 	TaskScheduler::~TaskScheduler()
89 	{
90 		int32 totalThreadsCount = GetWorkersCount();
91 		for (int32 i = 0; i < totalThreadsCount; i++)
92 		{
93 			threadContext[i].state.Store(internal::ThreadState::EXIT);
94 			threadContext[i].hasNewTasksEvent.Signal();
95 		}
96 
97 		for (int32 i = 0; i < totalThreadsCount; i++)
98 		{
99 			threadContext[i].thread.Stop();
100 		}
101 	}
102 
103 	ConcurrentQueueLIFO<FiberContext*>* TaskScheduler::GetFibersStorage(MT::StackRequirements::Type stackRequirements)
104 	{
105 		ConcurrentQueueLIFO<FiberContext*>* availableFibers = nullptr;
106 		switch(stackRequirements)
107 		{
108 		case MT::StackRequirements::STANDARD:
109 			availableFibers = &standartFibersAvailable;
110 			break;
111 		case MT::StackRequirements::EXTENDED:
112 			availableFibers = &extendedFibersAvailable;
113 			break;
114 		default:
115 			MT_REPORT_ASSERT("Unknown stack requrements");
116 		}
117 
118 		return availableFibers;
119 	}
120 
121 	FiberContext* TaskScheduler::RequestFiberContext(internal::GroupedTask& task)
122 	{
123 		FiberContext *fiberContext = task.awaitingFiber;
124 		if (fiberContext)
125 		{
126 			task.awaitingFiber = nullptr;
127 			return fiberContext;
128 		}
129 
130 
131 		MT::StackRequirements::Type stackRequirements = task.desc.stackRequirements;
132 
133 		ConcurrentQueueLIFO<FiberContext*>* availableFibers = GetFibersStorage(stackRequirements);
134 		MT_VERIFY(availableFibers != nullptr, "Can't find fiber storage", return nullptr;);
135 
136 		if (!availableFibers->TryPopBack(fiberContext))
137 		{
138 			MT_REPORT_ASSERT("Fibers pool is empty. Too many fibers running simultaneously.");
139 		}
140 
141 		fiberContext->currentTask = task.desc;
142 		fiberContext->currentGroup = task.group;
143 		fiberContext->parentFiber = task.parentFiber;
144 		fiberContext->stackRequirements = stackRequirements;
145 		return fiberContext;
146 	}
147 
148 	void TaskScheduler::ReleaseFiberContext(FiberContext* fiberContext)
149 	{
150 		MT_ASSERT(fiberContext != nullptr, "Can't release nullptr Fiber");
151 
152 		MT::StackRequirements::Type stackRequirements = fiberContext->stackRequirements;
153 		fiberContext->Reset();
154 
155 		ConcurrentQueueLIFO<FiberContext*>* availableFibers = GetFibersStorage(stackRequirements);
156 		MT_VERIFY(availableFibers != nullptr, "Can't find fiber storage", return;);
157 
158 		availableFibers->Push(fiberContext);
159 	}
160 
161 	FiberContext* TaskScheduler::ExecuteTask(internal::ThreadContext& threadContext, FiberContext* fiberContext)
162 	{
163 		MT_ASSERT(threadContext.thread.IsCurrentThread(), "Thread context sanity check failed");
164 
165 		MT_ASSERT(fiberContext, "Invalid fiber context");
166 		MT_ASSERT(fiberContext->currentTask.IsValid(), "Invalid task");
167 
168 		// Set actual thread context to fiber
169 		fiberContext->SetThreadContext(&threadContext);
170 
171 		// Update task status
172 		fiberContext->SetStatus(FiberTaskStatus::RUNNED);
173 
174 		MT_ASSERT(fiberContext->GetThreadContext()->thread.IsCurrentThread(), "Thread context sanity check failed");
175 
176 		const void* poolUserData = fiberContext->currentTask.userData;
177 		TPoolTaskDestroy poolDestroyFunc = fiberContext->currentTask.poolDestroyFunc;
178 
179 		// Run current task code
180 		Fiber::SwitchTo(threadContext.schedulerFiber, fiberContext->fiber);
181 
182 		// If task was done
183 		FiberTaskStatus::Type taskStatus = fiberContext->GetStatus();
184 		if (taskStatus == FiberTaskStatus::FINISHED)
185 		{
186 			//destroy task (call dtor) for "fire and forget" type of task from TaskPool
187 			if (poolDestroyFunc != nullptr)
188 			{
189 				poolDestroyFunc(poolUserData);
190 			}
191 
192 			TaskGroup taskGroup = fiberContext->currentGroup;
193 
194 			TaskScheduler::TaskGroupDescription  & groupDesc = threadContext.taskScheduler->GetGroupDesc(taskGroup);
195 
196 			// Update group status
197 			int groupTaskCount = groupDesc.Dec();
198 			MT_ASSERT(groupTaskCount >= 0, "Sanity check failed!");
199 			if (groupTaskCount == 0)
200 			{
201 				// Restore awaiting tasks
202 				threadContext.RestoreAwaitingTasks(taskGroup);
203 
204 				// All restored tasks can be already finished on this line.
205 				// That's why you can't release groups from worker threads, if worker thread release group, than you can't Signal to released group.
206 
207 				// Signal pending threads that group work is finished. Group can be destroyed after this call.
208 				groupDesc.Signal();
209 
210 				fiberContext->currentGroup = TaskGroup::INVALID;
211 			}
212 
213 			// Update total task count
214 			int allGroupTaskCount = threadContext.taskScheduler->allGroups.Dec();
215 			MT_ASSERT(allGroupTaskCount >= 0, "Sanity check failed!");
216 			if (allGroupTaskCount == 0)
217 			{
218 				// Notify all tasks in all group finished
219 				threadContext.taskScheduler->allGroups.Signal();
220 			}
221 
222 			FiberContext* parentFiberContext = fiberContext->parentFiber;
223 			if (parentFiberContext != nullptr)
224 			{
225 				int childrenFibersCount = parentFiberContext->childrenFibersCount.DecFetch();
226 				MT_ASSERT(childrenFibersCount >= 0, "Sanity check failed!");
227 
228 				if (childrenFibersCount == 0)
229 				{
230 					// This is a last subtask. Restore parent task
231 					MT_ASSERT(threadContext.thread.IsCurrentThread(), "Thread context sanity check failed");
232 					MT_ASSERT(parentFiberContext->GetThreadContext() == nullptr, "Inactive parent should not have a valid thread context");
233 
234 					// WARNING!! Thread context can changed here! Set actual current thread context.
235 					parentFiberContext->SetThreadContext(&threadContext);
236 
237 					MT_ASSERT(parentFiberContext->GetThreadContext()->thread.IsCurrentThread(), "Thread context sanity check failed");
238 
239 					// All subtasks is done.
240 					// Exiting and return parent fiber to scheduler
241 					return parentFiberContext;
242 				} else
243 				{
244 					// Other subtasks still exist
245 					// Exiting
246 					return nullptr;
247 				}
248 			} else
249 			{
250 				// Task is finished and no parent task
251 				// Exiting
252 				return nullptr;
253 			}
254 		}
255 
256 		MT_ASSERT(taskStatus != FiberTaskStatus::RUNNED, "Incorrect task status")
257 		return nullptr;
258 	}
259 
260 
261 	void TaskScheduler::FiberMain(void* userData)
262 	{
263 		FiberContext& fiberContext = *(FiberContext*)(userData);
264 		for(;;)
265 		{
266 			MT_ASSERT(fiberContext.currentTask.IsValid(), "Invalid task in fiber context");
267 			MT_ASSERT(fiberContext.GetThreadContext(), "Invalid thread context");
268 			MT_ASSERT(fiberContext.GetThreadContext()->thread.IsCurrentThread(), "Thread context sanity check failed");
269 
270 			fiberContext.currentTask.taskFunc( fiberContext, fiberContext.currentTask.userData );
271 
272 			fiberContext.SetStatus(FiberTaskStatus::FINISHED);
273 
274 #ifdef MT_INSTRUMENTED_BUILD
275 			fiberContext.GetThreadContext()->NotifyTaskFinished(fiberContext.currentTask);
276 #endif
277 
278 			Fiber::SwitchTo(fiberContext.fiber, fiberContext.GetThreadContext()->schedulerFiber);
279 		}
280 
281 	}
282 
283 
284 	bool TaskScheduler::TryStealTask(internal::ThreadContext& threadContext, internal::GroupedTask & task, uint32 workersCount)
285 	{
286 		if (workersCount <= 1)
287 		{
288 			return false;
289 		}
290 
291 		uint32 victimIndex = threadContext.random.Get();
292 
293 		for (uint32 attempt = 0; attempt < workersCount; attempt++)
294 		{
295 			uint32 index = victimIndex % workersCount;
296 			if (index == threadContext.workerIndex)
297 			{
298 				victimIndex++;
299 				index = victimIndex % workersCount;
300 			}
301 
302 			internal::ThreadContext& victimContext = threadContext.taskScheduler->threadContext[index];
303 			if (victimContext.queue.TryPopFront(task))
304 			{
305 				return true;
306 			}
307 
308 			victimIndex++;
309 		}
310 		return false;
311 	}
312 
313 
314 	void TaskScheduler::ThreadMain( void* userData )
315 	{
316 		internal::ThreadContext& context = *(internal::ThreadContext*)(userData);
317 		MT_ASSERT(context.taskScheduler, "Task scheduler must be not null!");
318 		context.schedulerFiber.CreateFromCurrentThreadAndRun(context.thread, ShedulerFiberMain, userData);
319 	}
320 
321 
322 	void TaskScheduler::ShedulerFiberMain( void* userData )
323 	{
324 		internal::ThreadContext& context = *(internal::ThreadContext*)(userData);
325 		MT_ASSERT(context.taskScheduler, "Task scheduler must be not null!");
326 
327 #ifdef MT_INSTRUMENTED_BUILD
328 		context.NotifyThreadCreate(context.workerIndex);
329 #endif
330 
331 
332 		uint32 workersCount = context.taskScheduler->GetWorkersCount();
333 
334 		int32 totalThreadsCount = context.taskScheduler->threadsCount.LoadRelaxed();
335 
336 		context.taskScheduler->startedThreadsCount.IncFetch();
337 
338 		//Simple spinlock until all threads is started and initialized
339 		for(;;)
340 		{
341 			int32 initializedThreadsCount = context.taskScheduler->startedThreadsCount.Load();
342 			if (initializedThreadsCount == totalThreadsCount)
343 			{
344 				break;
345 			}
346 			Thread::Sleep(1);
347 		}
348 
349 
350 		HardwareFullMemoryBarrier();
351 
352 #ifdef MT_INSTRUMENTED_BUILD
353 		context.NotifyThreadStart(context.workerIndex);
354 #endif
355 
356 		while(context.state.Load() != internal::ThreadState::EXIT)
357 		{
358 			internal::GroupedTask task;
359 			if (context.queue.TryPopBack(task) || TryStealTask(context, task, workersCount) )
360 			{
361 				// There is a new task
362 				FiberContext* fiberContext = context.taskScheduler->RequestFiberContext(task);
363 				MT_ASSERT(fiberContext, "Can't get execution context from pool");
364 				MT_ASSERT(fiberContext->currentTask.IsValid(), "Sanity check failed");
365 				MT_ASSERT(fiberContext->stackRequirements == task.desc.stackRequirements, "Sanity check failed");
366 
367 				while(fiberContext)
368 				{
369 #ifdef MT_INSTRUMENTED_BUILD
370 					context.NotifyTaskResumed(fiberContext->currentTask);
371 #endif
372 					// prevent invalid fiber resume from child tasks, before ExecuteTask is done
373 					fiberContext->childrenFibersCount.IncFetch();
374 
375 					FiberContext* parentFiber = ExecuteTask(context, fiberContext);
376 
377 					FiberTaskStatus::Type taskStatus = fiberContext->GetStatus();
378 
379 					//release guard
380 					int childrenFibersCount = fiberContext->childrenFibersCount.DecFetch();
381 
382 					// Can drop fiber context - task is finished
383 					if (taskStatus == FiberTaskStatus::FINISHED)
384 					{
385 						MT_ASSERT( childrenFibersCount == 0, "Sanity check failed");
386 						context.taskScheduler->ReleaseFiberContext(fiberContext);
387 
388 						// If parent fiber is exist transfer flow control to parent fiber, if parent fiber is null, exit
389 						fiberContext = parentFiber;
390 					} else
391 					{
392 						MT_ASSERT( childrenFibersCount >= 0, "Sanity check failed");
393 
394 						// No subtasks here and status is not finished, this mean all subtasks already finished before parent return from ExecuteTask
395 						if (childrenFibersCount == 0)
396 						{
397 							MT_ASSERT(parentFiber == nullptr, "Sanity check failed");
398 						} else
399 						{
400 							// If subtasks still exist, drop current task execution. task will be resumed when last subtask finished
401 							break;
402 						}
403 
404 						// If task is in await state drop execution. task will be resumed when RestoreAwaitingTasks called
405 						if (taskStatus == FiberTaskStatus::AWAITING_GROUP)
406 						{
407 							break;
408 						}
409 					}
410 				} //while(fiberContext)
411 
412 			} else
413 			{
414 #ifdef MT_INSTRUMENTED_BUILD
415 				context.NotifyThreadIdleBegin(context.workerIndex);
416 #endif
417 
418 				// Queue is empty and stealing attempt failed
419 				// Wait new events
420 				context.hasNewTasksEvent.Wait(2000);
421 
422 #ifdef MT_INSTRUMENTED_BUILD
423 				context.NotifyThreadIdleEnd(context.workerIndex);
424 #endif
425 
426 			}
427 
428 		} // main thread loop
429 
430 #ifdef MT_INSTRUMENTED_BUILD
431 		context.NotifyThreadStop(context.workerIndex);
432 #endif
433 
434 	}
435 
436 	void TaskScheduler::RunTasksImpl(ArrayView<internal::TaskBucket>& buckets, FiberContext * parentFiber, bool restoredFromAwaitState)
437 	{
438 		// This storage is necessary to calculate how many tasks we add to different groups
439 		int newTaskCountInGroup[TaskGroup::MT_MAX_GROUPS_COUNT];
440 
441 		// Default value is 0
442 		memset(&newTaskCountInGroup[0], 0, sizeof(newTaskCountInGroup));
443 
444 		// Set parent fiber pointer
445 		// Calculate the number of tasks per group
446 		// Calculate total number of tasks
447 		size_t count = 0;
448 		for (size_t i = 0; i < buckets.Size(); ++i)
449 		{
450 			internal::TaskBucket& bucket = buckets[i];
451 			for (size_t taskIndex = 0; taskIndex < bucket.count; taskIndex++)
452 			{
453 				internal::GroupedTask & task = bucket.tasks[taskIndex];
454 
455 				task.parentFiber = parentFiber;
456 
457 				int idx = task.group.GetValidIndex();
458 				MT_ASSERT(idx >= 0 && idx < TaskGroup::MT_MAX_GROUPS_COUNT, "Invalid index");
459 				newTaskCountInGroup[idx]++;
460 			}
461 
462 			count += bucket.count;
463 		}
464 
465 		// Increments child fibers count on parent fiber
466 		if (parentFiber)
467 		{
468 			parentFiber->childrenFibersCount.AddFetch((int)count);
469 		}
470 
471 		if (restoredFromAwaitState == false)
472 		{
473 			// Increase the number of active tasks in the group using data from temporary storage
474 			for (size_t i = 0; i < TaskGroup::MT_MAX_GROUPS_COUNT; i++)
475 			{
476 				int groupNewTaskCount = newTaskCountInGroup[i];
477 				if (groupNewTaskCount > 0)
478 				{
479 					groupStats[i].Reset();
480 					groupStats[i].Add((uint32)groupNewTaskCount);
481 				}
482 			}
483 
484 			// Increments all task in progress counter
485 			allGroups.Reset();
486 			allGroups.Add((uint32)count);
487 		} else
488 		{
489 			// If task's restored from await state, counters already in correct state
490 		}
491 
492 		// Add to thread queue
493 		for (size_t i = 0; i < buckets.Size(); ++i)
494 		{
495 			int bucketIndex = roundRobinThreadIndex.IncFetch() % threadsCount.LoadRelaxed();
496 			internal::ThreadContext & context = threadContext[bucketIndex];
497 
498 			internal::TaskBucket& bucket = buckets[i];
499 
500 			context.queue.PushRange(bucket.tasks, bucket.count);
501 			context.hasNewTasksEvent.Signal();
502 		}
503 	}
504 
505 	void TaskScheduler::RunAsync(TaskGroup group, const TaskHandle* taskHandleArray, uint32 taskHandleCount)
506 	{
507 		MT_ASSERT(!IsWorkerThread(), "Can't use RunAsync inside Task. Use FiberContext.RunAsync() instead.");
508 
509 		ArrayView<internal::GroupedTask> buffer(MT_ALLOCATE_ON_STACK(sizeof(internal::GroupedTask) * taskHandleCount), taskHandleCount);
510 
511 		uint32 bucketCount = MT::Min((uint32)GetWorkersCount(), taskHandleCount);
512 		ArrayView<internal::TaskBucket> buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount);
513 
514 		internal::DistibuteDescriptions(group, taskHandleArray, buffer, buckets);
515 		RunTasksImpl(buckets, nullptr, false);
516 	}
517 
518 	bool TaskScheduler::WaitGroup(TaskGroup group, uint32 milliseconds)
519 	{
520 		MT_VERIFY(IsWorkerThread() == false, "Can't use WaitGroup inside Task. Use FiberContext.WaitGroupAndYield() instead.", return false);
521 
522 		TaskScheduler::TaskGroupDescription  & groupDesc = GetGroupDesc(group);
523 		return groupDesc.Wait(milliseconds);
524 	}
525 
526 	bool TaskScheduler::WaitAll(uint32 milliseconds)
527 	{
528 		MT_VERIFY(IsWorkerThread() == false, "Can't use WaitAll inside Task.", return false);
529 
530 		return allGroups.Wait(milliseconds);
531 	}
532 
533 	bool TaskScheduler::IsEmpty()
534 	{
535 		for (uint32 i = 0; i < MT_MAX_THREAD_COUNT; i++)
536 		{
537 			if (!threadContext[i].queue.IsEmpty())
538 			{
539 				return false;
540 			}
541 		}
542 		return true;
543 	}
544 
545 	int32 TaskScheduler::GetWorkersCount() const
546 	{
547 		return threadsCount.LoadRelaxed();
548 	}
549 
550 	bool TaskScheduler::IsWorkerThread() const
551 	{
552 		for (uint32 i = 0; i < MT_MAX_THREAD_COUNT; i++)
553 		{
554 			if (threadContext[i].thread.IsCurrentThread())
555 			{
556 				return true;
557 			}
558 		}
559 		return false;
560 	}
561 
562 	TaskGroup TaskScheduler::CreateGroup()
563 	{
564 		MT_ASSERT(IsWorkerThread() == false, "Can't use CreateGroup inside Task.");
565 
566 		TaskGroup group;
567 		if (!availableGroups.TryPopBack(group))
568 		{
569 			MT_REPORT_ASSERT("Group pool is empty");
570 		}
571 
572 		int idx = group.GetValidIndex();
573 
574 		MT_ASSERT(groupStats[idx].GetDebugIsFree() == true, "Bad logic!");
575 		groupStats[idx].SetDebugIsFree(false);
576 
577 		return group;
578 	}
579 
580 	void TaskScheduler::ReleaseGroup(TaskGroup group)
581 	{
582 		MT_ASSERT(IsWorkerThread() == false, "Can't use ReleaseGroup inside Task.");
583 		MT_ASSERT(group.IsValid(), "Invalid group ID");
584 
585 		int idx = group.GetValidIndex();
586 
587 		MT_ASSERT(groupStats[idx].GetDebugIsFree() == false, "Group already released");
588 		groupStats[idx].SetDebugIsFree(true);
589 
590 		availableGroups.Push(group);
591 	}
592 
593 	TaskScheduler::TaskGroupDescription & TaskScheduler::GetGroupDesc(TaskGroup group)
594 	{
595 		MT_ASSERT(group.IsValid(), "Invalid group ID");
596 
597 		int idx = group.GetValidIndex();
598 		TaskScheduler::TaskGroupDescription & groupDesc = groupStats[idx];
599 
600 		MT_ASSERT(groupDesc.GetDebugIsFree() == false, "Invalid group");
601 		return groupDesc;
602 	}
603 }
604 
605 
606