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 	FiberContext::FiberContext()
28 		: threadContext(nullptr)
29 		, taskStatus(FiberTaskStatus::UNKNOWN)
30 		, stackRequirements(StackRequirements::INVALID)
31 		, childrenFibersCount(0)
32 		, parentFiber(nullptr)
33 	{
34 
35 	}
36 
37 	void FiberContext::SetStatus(FiberTaskStatus::Type _taskStatus)
38 	{
39 		MT_ASSERT(threadContext, "Sanity check failed");
40 		MT_ASSERT(threadContext->threadId.IsEqual(ThreadId::Self()), "You can change task status only from owner thread");
41 		taskStatus = _taskStatus;
42 	}
43 
44 	FiberTaskStatus::Type FiberContext::GetStatus() const
45 	{
46 		return taskStatus;
47 	}
48 
49 	void FiberContext::SetThreadContext(internal::ThreadContext * _threadContext)
50 	{
51 		if (_threadContext)
52 		{
53 			_threadContext->lastActiveFiberContext = this;
54 
55 #ifdef MT_INSTRUMENTED_BUILD
56 			_threadContext->NotifyFiberAssignedToThread( fiberIndex, _threadContext->workerIndex );
57 #endif
58 		}
59 
60 		threadContext = _threadContext;
61 	}
62 
63 	internal::ThreadContext* FiberContext::GetThreadContext()
64 	{
65 		return threadContext;
66 	}
67 
68 	void FiberContext::Reset()
69 	{
70 		MT_ASSERT(childrenFibersCount.Load() == 0, "Can't release fiber with active children fibers");
71 		currentTask = internal::TaskDesc();
72 		parentFiber = nullptr;
73 		threadContext = nullptr;
74 		stackRequirements = StackRequirements::INVALID;
75 	}
76 
77 	void FiberContext::Yield()
78 	{
79 		taskStatus = FiberTaskStatus::YIELDED;
80 
81 		Fiber & schedulerFiber = threadContext->schedulerFiber;
82 
83 #ifdef MT_INSTRUMENTED_BUILD
84 		threadContext->NotifyTaskExecuteStateChanged( currentTask.debugColor, currentTask.debugID, TaskExecuteState::SUSPEND );
85 #endif
86 
87 		// Yielding, so reset thread context
88 		threadContext = nullptr;
89 
90 		//switch to scheduler
91 		Fiber::SwitchTo(fiber, schedulerFiber);
92 
93 #ifdef MT_INSTRUMENTED_BUILD
94 		threadContext->NotifyTaskExecuteStateChanged( currentTask.debugColor, currentTask.debugID, TaskExecuteState::RESUME );
95 #endif
96 	}
97 
98 	void FiberContext::RunSubtasksAndYieldImpl(ArrayView<internal::TaskBucket>& buckets)
99 	{
100 		MT_ASSERT(threadContext, "Sanity check failed!");
101 		MT_ASSERT(threadContext->taskScheduler, "Sanity check failed!");
102 		MT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), "Can't use RunSubtasksAndYield outside Task. Use TaskScheduler.WaitGroup() instead.");
103 		MT_ASSERT(threadContext->threadId.IsEqual(ThreadId::Self()), "Thread context sanity check failed");
104 
105 		// add to scheduler
106 		threadContext->taskScheduler->RunTasksImpl(buckets, this, false);
107 
108 		//
109 		MT_ASSERT(threadContext->threadId.IsEqual(ThreadId::Self()), "Thread context sanity check failed");
110 
111 		// Change status
112 		taskStatus = FiberTaskStatus::AWAITING_CHILD;
113 
114 		Fiber & schedulerFiber = threadContext->schedulerFiber;
115 
116 #ifdef MT_INSTRUMENTED_BUILD
117 		threadContext->NotifyTaskExecuteStateChanged( currentTask.debugColor, currentTask.debugID, TaskExecuteState::SUSPEND );
118 #endif
119 
120 		// Yielding, so reset thread context
121 		threadContext = nullptr;
122 
123 		//switch to scheduler
124 		Fiber::SwitchTo(fiber, schedulerFiber);
125 
126 #ifdef MT_INSTRUMENTED_BUILD
127 		threadContext->NotifyTaskExecuteStateChanged( currentTask.debugColor, currentTask.debugID, TaskExecuteState::RESUME );
128 #endif
129 
130 	}
131 
132 
133 	void FiberContext::RunAsync(TaskGroup taskGroup, const TaskHandle* taskHandleArray, uint32 taskHandleCount)
134 	{
135 		MT_ASSERT(taskHandleCount < (internal::TASK_BUFFER_CAPACITY - 1), "Too many tasks per one Run.");
136 		MT_ASSERT(threadContext, "ThreadContext is nullptr");
137 		MT_ASSERT(threadContext->taskScheduler, "Sanity check failed!");
138 		MT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), "Can't use RunAsync outside Task. Use TaskScheduler.RunAsync() instead.");
139 
140 		TaskScheduler& scheduler = *(threadContext->taskScheduler);
141 
142 		ArrayView<internal::GroupedTask> buffer(threadContext->descBuffer, taskHandleCount);
143 
144 		uint32 bucketCount = MT::Min((uint32)scheduler.GetWorkersCount(), taskHandleCount);
145 		ArrayView<internal::TaskBucket>	buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount);
146 
147 		internal::DistibuteDescriptions(taskGroup, taskHandleArray, buffer, buckets);
148 		scheduler.RunTasksImpl(buckets, nullptr, false);
149 	}
150 
151 
152 	void FiberContext::RunSubtasksAndYield(TaskGroup taskGroup, const TaskHandle* taskHandleArray, uint32 taskHandleCount)
153 	{
154 		MT_ASSERT(taskHandleCount < (internal::TASK_BUFFER_CAPACITY - 1), "Too many tasks per one Run.");
155 		MT_ASSERT(threadContext, "ThreadContext is nullptr");
156 		MT_ASSERT(threadContext->taskScheduler, "TaskScheduler is nullptr");
157 
158 		TaskScheduler& scheduler = *(threadContext->taskScheduler);
159 
160 		ArrayView<internal::GroupedTask> buffer(threadContext->descBuffer, taskHandleCount);
161 
162 		uint32 bucketCount = MT::Min((uint32)scheduler.GetWorkersCount(), taskHandleCount);
163 		ArrayView<internal::TaskBucket> buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount);
164 
165 		internal::DistibuteDescriptions(taskGroup, taskHandleArray, buffer, buckets);
166 		RunSubtasksAndYieldImpl(buckets);
167 	}
168 
169 
170 
171 }
172