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