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 		static const size_t TASK_BUFFER_CAPACITY = 4096;
31 
32 		// Prime numbers for linear congruential generator seed
33 		static const uint32 primeNumbers[] = {
34 			128473, 135349, 159499, 173839, 209213, 241603, 292709, 314723,
35 			343943, 389299, 419473, 465169, 518327, 649921, 748271, 851087,
36 			862171, 974551, 1002973, 1034639, 1096289, 1153123, 1251037, 1299269,
37 			1272941, 1252151, 1231091, 1206761, 1185469, 1169933, 1141351, 1011583 };
38 
39 		uint32 GetPrimeNumber(uint32 index)
40 		{
41 			return primeNumbers[index % MT_ARRAY_SIZE(primeNumbers)];
42 		}
43 
44 
45 
46 		ThreadContext::ThreadContext()
47 			: lastActiveFiberContext(nullptr)
48 			, taskScheduler(nullptr)
49 			, hasNewTasksEvent(EventReset::AUTOMATIC, true)
50 			, state(ThreadState::ALIVE)
51 			, descBuffer(TASK_BUFFER_CAPACITY)
52 			, workerIndex(0)
53 		{
54 		}
55 
56 		ThreadContext::~ThreadContext()
57 		{
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.front(), 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 			ProfileEventDesc eventDesc;
98 			eventDesc.id = desc.debugID;
99 			eventDesc.colorIndex = desc.colorIndex;
100 			eventDesc.type = ProfileEventType::TASK_DONE;
101 			eventDesc.timeStampMicroSeconds = MT::GetTimeMicroSeconds() - taskScheduler->GetStartTime();
102 
103 			profileEvents.Push(std::move(eventDesc));
104 		}
105 
106 		void ThreadContext::NotifyTaskResumed(const internal::TaskDesc & desc)
107 		{
108 			ProfileEventDesc eventDesc;
109 			eventDesc.id = desc.debugID;
110 			eventDesc.colorIndex = desc.colorIndex;
111 			eventDesc.type = ProfileEventType::TASK_RESUME;
112 			eventDesc.timeStampMicroSeconds = MT::GetTimeMicroSeconds() - taskScheduler->GetStartTime();
113 			profileEvents.Push(std::move(eventDesc));
114 		}
115 
116 		void ThreadContext::NotifyTaskYielded(const internal::TaskDesc & desc)
117 		{
118 			ProfileEventDesc eventDesc;
119 			eventDesc.id = desc.debugID;
120 			eventDesc.colorIndex = desc.colorIndex;
121 			eventDesc.type = ProfileEventType::TASK_YIELD;
122 			eventDesc.timeStampMicroSeconds = MT::GetTimeMicroSeconds() - taskScheduler->GetStartTime();
123 			profileEvents.Push(std::move(eventDesc));
124 		}
125 
126 		void ThreadContext::NotifyWorkerAwait(int64 waitFrom, int64 waitTo)
127 		{
128 			waitFrom;
129 			waitTo;
130 /*
131 			if ((waitTo - waitFrom) > 100)
132 			{
133 				ProfileEventDesc eventDesc;
134 				eventDesc.id = "#";
135 				eventDesc.colorIndex = MT_COLOR_YELLOW;
136 				eventDesc.type = ProfileEventType::TASK_RESUME;
137 				eventDesc.timeStampMicroSeconds = waitFrom - MT::TaskScheduler::GetStartTime();
138 				profileEvents.Push(std::move(eventDesc));
139 
140 				eventDesc.id = "#";
141 				eventDesc.colorIndex = MT_COLOR_YELLOW;
142 				eventDesc.type = ProfileEventType::TASK_DONE;
143 				eventDesc.timeStampMicroSeconds = waitTo - MT::TaskScheduler::GetStartTime();
144 				profileEvents.Push(std::move(eventDesc));
145 			}
146 */
147 
148 		}
149 
150 
151 
152 #endif
153 
154 	}
155 
156 }
157