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