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