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