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 #include <MTStaticVector.h>
25 
26 namespace MT
27 {
28 	FiberContext::FiberContext()
29 		: threadContext(nullptr)
30 		, taskStatus(FiberTaskStatus::UNKNOWN)
31 		, stackRequirements(StackRequirements::INVALID)
32 		, childrenFibersCount(0)
33 		, parentFiber(nullptr)
34 	{
35 	}
36 
37 	void FiberContext::SetStatus(FiberTaskStatus::Type _taskStatus)
38 	{
39 		MT_ASSERT(threadContext, "Sanity check failed");
40 		MT_ASSERT(threadContext->thread.IsCurrentThread(), "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 
56 		threadContext = _threadContext;
57 	}
58 
59 	internal::ThreadContext* FiberContext::GetThreadContext()
60 	{
61 		return threadContext;
62 	}
63 
64 	void FiberContext::Reset()
65 	{
66 		MT_ASSERT(childrenFibersCount.Load() == 0, "Can't release fiber with active children fibers");
67 		currentTask = internal::TaskDesc();
68 		parentFiber = nullptr;
69 		threadContext = nullptr;
70 		stackRequirements = StackRequirements::INVALID;
71 	}
72 
73 	void FiberContext::Yield()
74 	{
75 		ArrayView<internal::GroupedTask> buffer(threadContext->descBuffer, 1);
76 		ArrayView<internal::TaskBucket> buckets( MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket)), 1 );
77 
78 		FiberContext* thisTask = this;
79 		StaticVector<FiberContext*, 1> yieldTaskQueue(1, thisTask);
80 		internal::DistibuteDescriptions( TaskGroup(TaskGroup::ASSIGN_FROM_CONTEXT), yieldTaskQueue.Begin(), buffer, buckets );
81 
82 		taskStatus = FiberTaskStatus::YIELDED;
83 
84 		TaskScheduler* taskScheduler = threadContext->taskScheduler;
85 		Fiber & schedulerFiber = threadContext->schedulerFiber;
86 
87 #ifdef MT_INSTRUMENTED_BUILD
88 		threadContext->NotifyTaskExecuteStateChanged( currentTask.debugColor, currentTask.debugID, TaskExecuteState::SUSPEND );
89 #endif
90 
91 		// Yielding, so reset thread context
92 		threadContext = nullptr;
93 
94 		// add task to scheduler
95 		taskScheduler->RunTasksImpl(buckets, nullptr, true);
96 
97 		// ATENTION! this task can be already completed at this point
98 
99 		//switch to scheduler
100 		Fiber::SwitchTo(fiber, schedulerFiber);
101 
102 #ifdef MT_INSTRUMENTED_BUILD
103 		threadContext->NotifyTaskExecuteStateChanged( currentTask.debugColor, currentTask.debugID, TaskExecuteState::RESUME );
104 #endif
105 	}
106 
107 	void FiberContext::RunSubtasksAndYieldImpl(ArrayView<internal::TaskBucket>& buckets)
108 	{
109 		MT_ASSERT(threadContext, "Sanity check failed!");
110 		MT_ASSERT(threadContext->taskScheduler, "Sanity check failed!");
111 		MT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), "Can't use RunSubtasksAndYield outside Task. Use TaskScheduler.WaitGroup() instead.");
112 		MT_ASSERT(threadContext->thread.IsCurrentThread(), "Thread context sanity check failed");
113 
114 		// add to scheduler
115 		threadContext->taskScheduler->RunTasksImpl(buckets, this, false);
116 
117 		//
118 		MT_ASSERT(threadContext->thread.IsCurrentThread(), "Thread context sanity check failed");
119 
120 		// Change status
121 		taskStatus = FiberTaskStatus::AWAITING_CHILD;
122 
123 		Fiber & schedulerFiber = threadContext->schedulerFiber;
124 
125 #ifdef MT_INSTRUMENTED_BUILD
126 		threadContext->NotifyTaskExecuteStateChanged( currentTask.debugColor, currentTask.debugID, TaskExecuteState::SUSPEND );
127 #endif
128 
129 		// Yielding, so reset thread context
130 		threadContext = nullptr;
131 
132 		//switch to scheduler
133 		Fiber::SwitchTo(fiber, schedulerFiber);
134 
135 #ifdef MT_INSTRUMENTED_BUILD
136 		threadContext->NotifyTaskExecuteStateChanged( currentTask.debugColor, currentTask.debugID, TaskExecuteState::RESUME );
137 #endif
138 
139 	}
140 
141 
142 	void FiberContext::RunAsync(TaskGroup taskGroup, const TaskHandle* taskHandleArray, uint32 taskHandleCount)
143 	{
144 		MT_ASSERT(threadContext, "ThreadContext is nullptr");
145 		MT_ASSERT(threadContext->taskScheduler, "Sanity check failed!");
146 		MT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), "Can't use RunAsync outside Task. Use TaskScheduler.RunAsync() instead.");
147 
148 		TaskScheduler& scheduler = *(threadContext->taskScheduler);
149 
150 		ArrayView<internal::GroupedTask> buffer(threadContext->descBuffer, taskHandleCount);
151 
152 		uint32 bucketCount = MT::Min((uint32)scheduler.GetWorkersCount(), taskHandleCount);
153 		ArrayView<internal::TaskBucket>	buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount);
154 
155 		internal::DistibuteDescriptions(taskGroup, taskHandleArray, buffer, buckets);
156 		scheduler.RunTasksImpl(buckets, nullptr, false);
157 	}
158 
159 
160 	void FiberContext::RunSubtasksAndYield(TaskGroup taskGroup, const TaskHandle* taskHandleArray, uint32 taskHandleCount)
161 	{
162 		MT_ASSERT(threadContext, "ThreadContext is nullptr");
163 		MT_ASSERT(threadContext->taskScheduler, "TaskScheduler is nullptr");
164 
165 		MT_ASSERT(taskHandleCount < internal::TASK_BUFFER_CAPACITY, "Buffer overrun!");
166 
167 		TaskScheduler& scheduler = *(threadContext->taskScheduler);
168 
169 		ArrayView<internal::GroupedTask> buffer(threadContext->descBuffer, taskHandleCount);
170 
171 		uint32 bucketCount = MT::Min((uint32)scheduler.GetWorkersCount(), taskHandleCount);
172 		ArrayView<internal::TaskBucket> buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount);
173 
174 		internal::DistibuteDescriptions(taskGroup, taskHandleArray, buffer, buckets);
175 		RunSubtasksAndYieldImpl(buckets);
176 	}
177 
178 
179 
180 }
181