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 			StackArray<FiberContext*, MT_MAX_FIBERS_COUNT> groupQueueCopy(MT_MAX_FIBERS_COUNT, nullptr);
81 			size_t taskCount = groupQueue.PopAll(groupQueueCopy.Begin(), groupQueueCopy.Size());
82 
83 			ArrayView<internal::GroupedTask> buffer(descBuffer, taskCount);
84 
85 			TaskScheduler & scheduler = *(taskScheduler);
86 			size_t bucketCount = MT::Min((size_t)scheduler.GetWorkerCount(), taskCount);
87 			ArrayView<internal::TaskBucket>	buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount);
88 
89 			internal::DistibuteDescriptions( TaskGroup(TaskGroup::ASSIGN_FROM_CONTEXT), groupQueueCopy.Begin(), buffer, buckets);
90 			scheduler.RunTasksImpl(buckets, nullptr, true);
91 		}
92 
93 #ifdef MT_INSTRUMENTED_BUILD
94 
95 		void ThreadContext::NotifyTaskFinished(const internal::TaskDesc & desc)
96 		{
97 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
98 			{
99 				eventListener->OnTaskFinished(desc.debugColor, desc.debugID);
100 			}
101 		}
102 
103 		void ThreadContext::NotifyTaskResumed(const internal::TaskDesc & desc)
104 		{
105 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
106 			{
107 				eventListener->OnTaskResumed(desc.debugColor, desc.debugID);
108 			}
109 
110 		}
111 
112 		void ThreadContext::NotifyTaskYielded(const internal::TaskDesc & desc)
113 		{
114 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
115 			{
116 				eventListener->OnTaskYielded(desc.debugColor, desc.debugID);
117 			}
118 		}
119 
120 		void ThreadContext::NotifyThreadCreate(uint32 threadIndex)
121 		{
122 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
123 			{
124 				eventListener->OnThreadCreated(threadIndex);
125 			}
126 		}
127 
128 		void ThreadContext::NotifyThreadStart(uint32 threadIndex)
129 		{
130 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
131 			{
132 				eventListener->OnThreadStarted(threadIndex);
133 			}
134 		}
135 
136 		void ThreadContext::NotifyThreadStop(uint32 threadIndex)
137 		{
138 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
139 			{
140 				eventListener->OnThreadStoped(threadIndex);
141 			}
142 		}
143 
144 
145 		void ThreadContext::NotifyThreadIdleBegin(uint32 threadIndex)
146 		{
147 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
148 			{
149 				eventListener->OnThreadIdleBegin(threadIndex);
150 			}
151 		}
152 
153 		void ThreadContext::NotifyThreadIdleEnd(uint32 threadIndex)
154 		{
155 			if (IProfilerEventListener* eventListener = taskScheduler->GetProfilerEventListener())
156 			{
157 				eventListener->OnThreadIdleEnd(threadIndex);
158 			}
159 		}
160 
161 
162 
163 
164 #endif
165 
166 	}
167 
168 }
169