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 
25 namespace MT
26 {
27 	namespace internal
28 	{
29 		static const size_t TASK_BUFFER_CAPACITY = 4096;
30 
31 		ThreadContext::ThreadContext()
32 			: lastActiveFiberContext(nullptr)
33 			, taskScheduler(nullptr)
34 			, hasNewTasksEvent(EventReset::AUTOMATIC, true)
35 			, state(ThreadState::ALIVE)
36 			, descBuffer(TASK_BUFFER_CAPACITY)
37 		{
38 		}
39 
40 		ThreadContext::~ThreadContext()
41 		{
42 		}
43 
44 		void ThreadContext::RestoreAwaitingTasks(TaskGroup::Type taskGroup)
45 		{
46 			ASSERT(taskScheduler, "Invalid Task Scheduler");
47 			ASSERT(taskScheduler->IsWorkerThread(), "Can't use RunAsync outside Task. Use TaskScheduler.RunAsync() instead.");
48 
49 			ConcurrentQueueLIFO<FiberContext*> & groupQueue = taskScheduler->waitTaskQueues[taskGroup];
50 
51 			if (groupQueue.IsEmpty())
52 			{
53 				return;
54 			}
55 
56 			//copy awaiting tasks list to stack
57 			stack_array<FiberContext*, MT_MAX_FIBERS_COUNT> groupQueueCopy(MT_MAX_FIBERS_COUNT, nullptr);
58 			size_t taskCount = groupQueue.PopAll(groupQueueCopy.begin(), groupQueueCopy.size());
59 
60 			fixed_array<internal::GroupedTask> buffer(&descBuffer.front(), taskCount);
61 
62 			TaskScheduler & scheduler = *(taskScheduler);
63 			size_t bucketCount = Min((size_t)scheduler.GetWorkerCount(), taskCount);
64 			fixed_array<internal::TaskBucket>	buckets(ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount);
65 
66 			internal::DistibuteDescriptions(TaskGroup::GROUP_UNDEFINED, groupQueueCopy.begin(), buffer, buckets);
67 			scheduler.RunTasksImpl(buckets, nullptr, true);
68 		}
69 
70 	}
71 
72 }
73