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