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 #ifdef MT_INSTRUMENTED_BUILD
34 		webServerPort = profilerWebServer.Serve(8080, 8090);
35 
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.TryPop(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 #if MT_FIBER_DEBUG
179 
180 					int ownerThread = parentFiberContext->fiber.GetOwnerThread();
181 					FiberTaskStatus::Type parentTaskStatus = parentFiberContext->GetStatus();
182 					internal::ThreadContext * parentThreadContext = parentFiberContext->GetThreadContext();
183 					int fiberUsageCounter = parentFiberContext->fiber.GetUsageCounter();
184 					MT_ASSERT(fiberUsageCounter == 0, "Parent fiber in invalid state");
185 
186 					ownerThread;
187 					parentTaskStatus;
188 					parentThreadContext;
189 					fiberUsageCounter;
190 #endif
191 
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.TryPop(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 		context.schedulerFiber.CreateFromThread(context.thread);
279 
280 		uint32 workersCount = context.taskScheduler->GetWorkerCount();
281 
282 		context.taskScheduler->startedThreadsCount.Inc();
283 
284 		//Spinlock until all threads started and initialized
285 		while(true)
286 		{
287 			if (context.taskScheduler->startedThreadsCount.Get() == (int)context.taskScheduler->threadsCount)
288 			{
289 				break;
290 			}
291 			Thread::Sleep(1);
292 		}
293 
294 		while(context.state.Get() != internal::ThreadState::EXIT)
295 		{
296 			internal::GroupedTask task;
297 			if (context.queue.TryPop(task) || TryStealTask(context, task, workersCount) )
298 			{
299 				// There is a new task
300 				FiberContext* fiberContext = context.taskScheduler->RequestFiberContext(task);
301 				MT_ASSERT(fiberContext, "Can't get execution context from pool");
302 				MT_ASSERT(fiberContext->currentTask.IsValid(), "Sanity check failed");
303 
304 				while(fiberContext)
305 				{
306 #ifdef MT_INSTRUMENTED_BUILD
307 					context.NotifyTaskResumed(fiberContext->currentTask);
308 #endif
309 
310 					// prevent invalid fiber resume from child tasks, before ExecuteTask is done
311 					fiberContext->childrenFibersCount.Inc();
312 
313 					FiberContext* parentFiber = ExecuteTask(context, fiberContext);
314 
315 					FiberTaskStatus::Type taskStatus = fiberContext->GetStatus();
316 
317 					//release guard
318 					int childrenFibersCount = fiberContext->childrenFibersCount.Dec();
319 
320 					// Can drop fiber context - task is finished
321 					if (taskStatus == FiberTaskStatus::FINISHED)
322 					{
323 						MT_ASSERT( childrenFibersCount == 0, "Sanity check failed");
324 						context.taskScheduler->ReleaseFiberContext(fiberContext);
325 
326 						// If parent fiber is exist transfer flow control to parent fiber, if parent fiber is null, exit
327 						fiberContext = parentFiber;
328 					} else
329 					{
330 						MT_ASSERT( childrenFibersCount >= 0, "Sanity check failed");
331 
332 						// No subtasks here and status is not finished, this mean all subtasks already finished before parent return from ExecuteTask
333 						if (childrenFibersCount == 0)
334 						{
335 							MT_ASSERT(parentFiber == nullptr, "Sanity check failed");
336 						} else
337 						{
338 							// If subtasks still exist, drop current task execution. task will be resumed when last subtask finished
339 							break;
340 						}
341 
342 						// If task is in await state drop execution. task will be resumed when RestoreAwaitingTasks called
343 						if (taskStatus == FiberTaskStatus::AWAITING_GROUP)
344 						{
345 							break;
346 						}
347 					}
348 				} //while(fiberContext)
349 
350 			} else
351 			{
352 #ifdef MT_INSTRUMENTED_BUILD
353 				int64 waitFrom = MT::GetTimeMicroSeconds();
354 #endif
355 
356 				// Queue is empty and stealing attempt failed
357 				// Wait new events
358 				context.hasNewTasksEvent.Wait(2000);
359 
360 #ifdef MT_INSTRUMENTED_BUILD
361 				int64 waitTo = MT::GetTimeMicroSeconds();
362 				context.NotifyWorkerAwait(waitFrom, waitTo);
363 #endif
364 
365 			}
366 
367 		} // main thread loop
368 	}
369 
370 	void TaskScheduler::RunTasksImpl(ArrayView<internal::TaskBucket>& buckets, FiberContext * parentFiber, bool restoredFromAwaitState)
371 	{
372 		// This storage is necessary to calculate how many tasks we add to different groups
373 		int newTaskCountInGroup[TaskGroup::MT_MAX_GROUPS_COUNT];
374 
375 		// Default value is 0
376 		memset(&newTaskCountInGroup[0], 0, sizeof(newTaskCountInGroup));
377 
378 		// Set parent fiber pointer
379 		// Calculate the number of tasks per group
380 		// Calculate total number of tasks
381 		size_t count = 0;
382 		for (size_t i = 0; i < buckets.Size(); ++i)
383 		{
384 			internal::TaskBucket& bucket = buckets[i];
385 			for (size_t taskIndex = 0; taskIndex < bucket.count; taskIndex++)
386 			{
387 				internal::GroupedTask & task = bucket.tasks[taskIndex];
388 
389 				task.parentFiber = parentFiber;
390 
391 				int idx = task.group.GetValidIndex();
392 				MT_ASSERT(idx >= 0 && idx < TaskGroup::MT_MAX_GROUPS_COUNT, "Invalid index");
393 				newTaskCountInGroup[idx]++;
394 			}
395 
396 			count += bucket.count;
397 		}
398 
399 		// Increments child fibers count on parent fiber
400 		if (parentFiber)
401 		{
402 			parentFiber->childrenFibersCount.Add((uint32)count);
403 		}
404 
405 		if (restoredFromAwaitState == false)
406 		{
407 			// Increase the number of active tasks in the group using data from temporary storage
408 			for (size_t i = 0; i < TaskGroup::MT_MAX_GROUPS_COUNT; i++)
409 			{
410 				int groupNewTaskCount = newTaskCountInGroup[i];
411 				if (groupNewTaskCount > 0)
412 				{
413 					groupStats[i].Reset();
414 					groupStats[i].Add((uint32)groupNewTaskCount);
415 				}
416 			}
417 
418 			// Increments all task in progress counter
419 			allGroups.Reset();
420 			allGroups.Add((uint32)count);
421 		} else
422 		{
423 			// If task's restored from await state, counters already in correct state
424 		}
425 
426 		// Add to thread queue
427 		for (size_t i = 0; i < buckets.Size(); ++i)
428 		{
429 			int bucketIndex = roundRobinThreadIndex.Inc() % threadsCount;
430 			internal::ThreadContext & context = threadContext[bucketIndex];
431 
432 			internal::TaskBucket& bucket = buckets[i];
433 
434 			context.queue.PushRange(bucket.tasks, bucket.count);
435 			context.hasNewTasksEvent.Signal();
436 		}
437 	}
438 
439 	bool TaskScheduler::WaitGroup(TaskGroup group, uint32 milliseconds)
440 	{
441 		MT_VERIFY(IsWorkerThread() == false, "Can't use WaitGroup inside Task. Use FiberContext.WaitGroupAndYield() instead.", return false);
442 
443 		TaskScheduler::TaskGroupDescription  & groupDesc = GetGroupDesc(group);
444 		return groupDesc.Wait(milliseconds);
445 	}
446 
447 	bool TaskScheduler::WaitAll(uint32 milliseconds)
448 	{
449 		MT_VERIFY(IsWorkerThread() == false, "Can't use WaitAll inside Task.", return false);
450 
451 		return allGroups.Wait(milliseconds);
452 	}
453 
454 	bool TaskScheduler::IsEmpty()
455 	{
456 		for (uint32 i = 0; i < MT_MAX_THREAD_COUNT; i++)
457 		{
458 			if (!threadContext[i].queue.IsEmpty())
459 			{
460 				return false;
461 			}
462 		}
463 		return true;
464 	}
465 
466 	uint32 TaskScheduler::GetWorkerCount() const
467 	{
468 		return threadsCount;
469 	}
470 
471 	bool TaskScheduler::IsWorkerThread() const
472 	{
473 		for (uint32 i = 0; i < MT_MAX_THREAD_COUNT; i++)
474 		{
475 			if (threadContext[i].thread.IsCurrentThread())
476 			{
477 				return true;
478 			}
479 		}
480 		return false;
481 	}
482 
483 	TaskGroup TaskScheduler::CreateGroup()
484 	{
485 		MT_ASSERT(IsWorkerThread() == false, "Can't use CreateGroup inside Task.");
486 
487 		TaskGroup group;
488 		if (!availableGroups.TryPop(group))
489 		{
490 			MT_ASSERT(false, "Group pool is empty");
491 		}
492 
493 		int idx = group.GetValidIndex();
494 
495 		MT_ASSERT(groupStats[idx].debugIsFree == true, "Bad logic!");
496 		groupStats[idx].debugIsFree = false;
497 
498 		return group;
499 	}
500 
501 	void TaskScheduler::ReleaseGroup(TaskGroup group)
502 	{
503 		MT_ASSERT(IsWorkerThread() == false, "Can't use ReleaseGroup inside Task.");
504 		MT_ASSERT(group.IsValid(), "Invalid group ID");
505 
506 		int idx = group.GetValidIndex();
507 
508 		MT_ASSERT(groupStats[idx].debugIsFree == false, "Group already released");
509 		groupStats[idx].debugIsFree = true;
510 
511 		availableGroups.Push(group);
512 	}
513 
514 	TaskScheduler::TaskGroupDescription & TaskScheduler::GetGroupDesc(TaskGroup group)
515 	{
516 		MT_ASSERT(group.IsValid(), "Invalid group ID");
517 
518 		int idx = group.GetValidIndex();
519 		TaskScheduler::TaskGroupDescription & groupDesc = groupStats[idx];
520 
521 		MT_ASSERT(groupDesc.debugIsFree == false, "Invalid group");
522 		return groupDesc;
523 	}
524 
525 
526 #ifdef MT_INSTRUMENTED_BUILD
527 
528 	size_t TaskScheduler::GetProfilerEvents(uint32 workerIndex, ProfileEventDesc * dstBuffer, size_t dstBufferSize)
529 	{
530 		if (workerIndex >= MT_MAX_THREAD_COUNT)
531 		{
532 			return 0;
533 		}
534 
535 		size_t elementsCount = threadContext[workerIndex].profileEvents.PopAll(dstBuffer, dstBufferSize);
536 		return elementsCount;
537 	}
538 
539 	void TaskScheduler::UpdateProfiler()
540 	{
541 		profilerWebServer.Update(*this);
542 	}
543 
544 	int32 TaskScheduler::GetWebServerPort() const
545 	{
546 		return webServerPort;
547 	}
548 
549 
550 
551 #endif
552 }
553