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 
26 namespace MT
27 {
28 	namespace internal
29 	{
30 		// Prime numbers for linear congruential generator seed
31 		static const uint32 primeNumbers[] = {
32 			128473, 135349, 159499, 173839, 209213, 241603, 292709, 314723,
33 			343943, 389299, 419473, 465169, 518327, 649921, 748271, 851087,
34 			862171, 974551, 1002973, 1034639, 1096289, 1153123, 1251037, 1299269,
35 			1272941, 1252151, 1231091, 1206761, 1185469, 1169933, 1141351, 1011583 };
36 
37 		uint32 GetPrimeNumber(uint32 index)
38 		{
39 			return primeNumbers[index % MT_ARRAY_SIZE(primeNumbers)];
40 		}
41 
42 
43 
44 		ThreadContext::ThreadContext()
45 			: lastActiveFiberContext(nullptr)
46 			, taskScheduler(nullptr)
47 			, hasNewTasksEvent(EventReset::AUTOMATIC, true)
48 			, state(ThreadState::ALIVE)
49 			, workerIndex(0)
50 		{
51 			 descBuffer = Memory::Alloc( sizeof(internal::GroupedTask) * TASK_BUFFER_CAPACITY );
52 		}
53 
54 		ThreadContext::~ThreadContext()
55 		{
56 			Memory::Free(descBuffer);
57 			descBuffer = nullptr;
58 		}
59 
60 		void ThreadContext::SetThreadIndex(uint32 threadIndex)
61 		{
62 			workerIndex = threadIndex;
63 			random.SetSeed( GetPrimeNumber(threadIndex) );
64 		}
65 
66 		void ThreadContext::RestoreAwaitingTasks(TaskGroup taskGroup)
67 		{
68 			MT_ASSERT(taskScheduler, "Invalid Task Scheduler");
69 			MT_ASSERT(taskScheduler->IsWorkerThread(), "Can't use RunAsync outside Task. Use TaskScheduler.RunAsync() instead.");
70 
71 			TaskScheduler::TaskGroupDescription  & groupDesc = taskScheduler->GetGroupDesc(taskGroup);
72 			ConcurrentQueueLIFO<FiberContext*> & groupQueue = groupDesc.GetWaitQueue();
73 
74 			if (groupQueue.IsEmpty())
75 			{
76 				return;
77 			}
78 
79 			//copy awaiting tasks list to stack
80 			const int maximumFibersCount = MT_MAX_STANDART_FIBERS_COUNT + MT_MAX_EXTENDED_FIBERS_COUNT;
81 			StackArray<FiberContext*, maximumFibersCount> groupQueueCopy(maximumFibersCount, nullptr);
82 			size_t taskCount = groupQueue.PopAll(groupQueueCopy.Begin(), groupQueueCopy.Size());
83 
84 			ArrayView<internal::GroupedTask> buffer(descBuffer, taskCount);
85 
86 			TaskScheduler & scheduler = *(taskScheduler);
87 			size_t bucketCount = MT::Min((size_t)scheduler.GetWorkersCount(), taskCount);
88 			ArrayView<internal::TaskBucket>	buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount);
89 
90 			internal::DistibuteDescriptions( TaskGroup(TaskGroup::ASSIGN_FROM_CONTEXT), groupQueueCopy.Begin(), buffer, buckets);
91 			scheduler.RunTasksImpl(buckets, nullptr, true);
92 		}
93 
94 #ifdef MT_INSTRUMENTED_BUILD
95 
96 		void ThreadContext::NotifyTaskFinished(const internal::TaskDesc & desc)
97 		{
98 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
99 			{
100 				eventListener->OnTaskFinished(desc.debugColor, desc.debugID);
101 			}
102 		}
103 
104 		void ThreadContext::NotifyTaskResumed(const internal::TaskDesc & desc)
105 		{
106 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
107 			{
108 				eventListener->OnTaskResumed(desc.debugColor, desc.debugID);
109 			}
110 
111 		}
112 
113 		void ThreadContext::NotifyTaskYielded(const internal::TaskDesc & desc)
114 		{
115 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
116 			{
117 				eventListener->OnTaskYielded(desc.debugColor, desc.debugID);
118 			}
119 		}
120 
121 		void ThreadContext::NotifyThreadCreate(uint32 threadIndex)
122 		{
123 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
124 			{
125 				eventListener->OnThreadCreated(threadIndex);
126 			}
127 		}
128 
129 		void ThreadContext::NotifyThreadStart(uint32 threadIndex)
130 		{
131 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
132 			{
133 				eventListener->OnThreadStarted(threadIndex);
134 			}
135 		}
136 
137 		void ThreadContext::NotifyThreadStop(uint32 threadIndex)
138 		{
139 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
140 			{
141 				eventListener->OnThreadStoped(threadIndex);
142 			}
143 		}
144 
145 
146 		void ThreadContext::NotifyThreadIdleBegin(uint32 threadIndex)
147 		{
148 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
149 			{
150 				eventListener->OnThreadIdleBegin(threadIndex);
151 			}
152 		}
153 
154 		void ThreadContext::NotifyThreadIdleEnd(uint32 threadIndex)
155 		{
156 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
157 			{
158 				eventListener->OnThreadIdleEnd(threadIndex);
159 			}
160 		}
161 
162 #endif
163 
164 	}
165 
166 }
167