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 
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 		taskStatus = FiberTaskStatus::YIELDED;
76 
77 		Fiber & schedulerFiber = threadContext->schedulerFiber;
78 
79 #ifdef MT_INSTRUMENTED_BUILD
80 		threadContext->NotifyTaskExecuteStateChanged( currentTask.debugColor, currentTask.debugID, TaskExecuteState::SUSPEND, (int32)fiberIndex);
81 #endif
82 
83 		// Yielding, so reset thread context
84 		threadContext = nullptr;
85 
86 		//switch to scheduler
87 		Fiber::SwitchTo(fiber, schedulerFiber);
88 
89 #ifdef MT_INSTRUMENTED_BUILD
90 		threadContext->NotifyTaskExecuteStateChanged( currentTask.debugColor, currentTask.debugID, TaskExecuteState::RESUME, (int32)fiberIndex);
91 #endif
92 	}
93 
94 	void FiberContext::RunSubtasksAndYieldImpl(ArrayView<internal::TaskBucket>& buckets)
95 	{
96 		MT_ASSERT(threadContext, "Sanity check failed!");
97 		MT_ASSERT(threadContext->taskScheduler, "Sanity check failed!");
98 		MT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), "Can't use RunSubtasksAndYield outside Task. Use TaskScheduler.WaitGroup() instead.");
99 		MT_ASSERT(threadContext->threadId.IsEqual(ThreadId::Self()), "Thread context sanity check failed");
100 
101 		// add to scheduler
102 		threadContext->taskScheduler->RunTasksImpl(buckets, this, false);
103 
104 		//
105 		MT_ASSERT(threadContext->threadId.IsEqual(ThreadId::Self()), "Thread context sanity check failed");
106 
107 		// Change status
108 		taskStatus = FiberTaskStatus::AWAITING_CHILD;
109 
110 		Fiber & schedulerFiber = threadContext->schedulerFiber;
111 
112 #ifdef MT_INSTRUMENTED_BUILD
113 		threadContext->NotifyTaskExecuteStateChanged( currentTask.debugColor, currentTask.debugID, TaskExecuteState::SUSPEND, (int32)fiberIndex);
114 #endif
115 
116 		// Yielding, so reset thread context
117 		threadContext = nullptr;
118 
119 		//switch to scheduler
120 		Fiber::SwitchTo(fiber, schedulerFiber);
121 
122 #ifdef MT_INSTRUMENTED_BUILD
123 		threadContext->NotifyTaskExecuteStateChanged( currentTask.debugColor, currentTask.debugID, TaskExecuteState::RESUME, (int32)fiberIndex);
124 #endif
125 
126 	}
127 
128 
129 	void FiberContext::RunAsync(TaskGroup taskGroup, const TaskHandle* taskHandleArray, uint32 taskHandleCount)
130 	{
131 		MT_ASSERT(taskHandleCount < (internal::TASK_BUFFER_CAPACITY - 1), "Too many tasks per one Run.");
132 		MT_ASSERT(threadContext, "ThreadContext is nullptr");
133 		MT_ASSERT(threadContext->taskScheduler, "Sanity check failed!");
134 		MT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), "Can't use RunAsync outside Task. Use TaskScheduler.RunAsync() instead.");
135 
136 		TaskScheduler& scheduler = *(threadContext->taskScheduler);
137 
138 		ArrayView<internal::GroupedTask> buffer(threadContext->descBuffer, taskHandleCount);
139 
140 		uint32 bucketCount = MT::Min((uint32)scheduler.GetWorkersCount(), taskHandleCount);
141 		ArrayView<internal::TaskBucket>	buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount);
142 
143 		internal::DistibuteDescriptions(taskGroup, taskHandleArray, buffer, buckets);
144 		scheduler.RunTasksImpl(buckets, nullptr, false);
145 	}
146 
147 
148 	void FiberContext::RunSubtasksAndYield(TaskGroup taskGroup, const TaskHandle* taskHandleArray, uint32 taskHandleCount)
149 	{
150 		MT_ASSERT(taskHandleCount < (internal::TASK_BUFFER_CAPACITY - 1), "Too many tasks per one Run.");
151 		MT_ASSERT(threadContext, "ThreadContext is nullptr");
152 		MT_ASSERT(threadContext->taskScheduler, "TaskScheduler is nullptr");
153 
154 		TaskScheduler& scheduler = *(threadContext->taskScheduler);
155 
156 		ArrayView<internal::GroupedTask> buffer(threadContext->descBuffer, taskHandleCount);
157 
158 		uint32 bucketCount = MT::Min((uint32)scheduler.GetWorkersCount(), taskHandleCount);
159 		ArrayView<internal::TaskBucket> buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount);
160 
161 		internal::DistibuteDescriptions(taskGroup, taskHandleArray, buffer, buckets);
162 		RunSubtasksAndYieldImpl(buckets);
163 	}
164 
165 
166 
167 }
168