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 #pragma once
24 
25 #include <MTTools.h>
26 #include <MTPlatform.h>
27 #include <MTConcurrentQueueLIFO.h>
28 #include <MTStackArray.h>
29 #include <MTArrayView.h>
30 #include <MTThreadContext.h>
31 #include <MTFiberContext.h>
32 #include <MTTaskBase.h>
33 
34 #ifdef MT_INSTRUMENTED_BUILD
35 #include <MTMicroWebSrv.h>
36 #endif
37 
38 namespace MT
39 {
40 	const uint32 MT_MAX_THREAD_COUNT = 32;
41 	const uint32 MT_MAX_FIBERS_COUNT = 128;
42 	const uint32 MT_SCHEDULER_STACK_SIZE = 131072;
43 	const uint32 MT_FIBER_STACK_SIZE = 32768;
44 
45 	namespace internal
46 	{
47 		struct ThreadContext;
48 	}
49 
50 	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
51 	// Task scheduler
52 	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
53 	class TaskScheduler
54 	{
55 		friend class FiberContext;
56 		friend struct internal::ThreadContext;
57 
58 		struct GroupStats
59 		{
60 			AtomicInt inProgressTaskCount;
61 			Event allDoneEvent;
62 
63 			GroupStats()
64 			{
65 				inProgressTaskCount.Set(0);
66 				allDoneEvent.Create( EventReset::MANUAL, true );
67 			}
68 		};
69 
70 		// Thread index for new task
71 		AtomicInt roundRobinThreadIndex;
72 
73 		// Threads created by task manager
74 		uint32 threadsCount;
75 		internal::ThreadContext threadContext[MT_MAX_THREAD_COUNT];
76 
77 		// Per group task statistic
78 		GroupStats groupStats[TaskGroup::COUNT];
79 
80 		// All groups task statistic
81 		GroupStats allGroupStats;
82 
83 
84 		//Task awaiting group through FiberContext::WaitGroupAndYield call
85 		ConcurrentQueueLIFO<FiberContext*> waitTaskQueues[TaskGroup::COUNT];
86 
87 
88 		// Fibers pool
89 		ConcurrentQueueLIFO<FiberContext*> availableFibers;
90 
91 		// Fibers context
92 		FiberContext fiberContext[MT_MAX_FIBERS_COUNT];
93 
94 #ifdef MT_INSTRUMENTED_BUILD
95 		int32 webServerPort;
96 		profile::MicroWebServer profilerWebServer;
97 		int64 startTime;
98 #endif
99 
100 		FiberContext* RequestFiberContext(internal::GroupedTask& task);
101 		void ReleaseFiberContext(FiberContext* fiberExecutionContext);
102 		void RunTasksImpl(ArrayView<internal::TaskBucket>& buckets, FiberContext * parentFiber, bool restoredFromAwaitState);
103 
104 		static void ThreadMain( void* userData );
105 		static void FiberMain( void* userData );
106 		static bool TryStealTask(internal::ThreadContext& threadContext, internal::GroupedTask & task, uint32 workersCount);
107 
108 		static FiberContext* ExecuteTask (internal::ThreadContext& threadContext, FiberContext* fiberContext);
109 
110 	public:
111 
112 		/// \brief Initializes a new instance of the TaskScheduler class.
113 		/// \param workerThreadsCount Worker threads count. Automatically determines the required number of threads if workerThreadsCount set to 0
114 		TaskScheduler(uint32 workerThreadsCount = 0);
115 		~TaskScheduler();
116 
117 		template<class TTask>
118 		void RunAsync(TaskGroup::Type group, TTask* taskArray, uint32 taskCount);
119 
120 		bool WaitGroup(TaskGroup::Type group, uint32 milliseconds);
121 		bool WaitAll(uint32 milliseconds);
122 
123 		bool IsEmpty();
124 
125 		uint32 GetWorkerCount() const;
126 
127 		bool IsWorkerThread() const;
128 
129 #ifdef MT_INSTRUMENTED_BUILD
130 
131 		size_t GetProfilerEvents(uint32 workerIndex, MT::ProfileEventDesc * dstBuffer, size_t dstBufferSize);
132 		void UpdateProfiler();
133 		int32 GetWebServerPort() const;
134 
135 		inline int64 GetStartTime() const
136 		{
137 			return startTime;
138 		}
139 
140 #endif
141 	};
142 }
143 
144 #include "MTScheduler.inl"
145 #include "MTFiberContext.inl"
146