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