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 #ifndef __MT_THREAD__
26 #define __MT_THREAD__
27 
28 
29 #include <pthread.h>
30 #include <unistd.h>
31 #include <time.h>
32 #include <limits.h>
33 #include <stdlib.h>
34 
35 #ifdef __APPLE_CC__
36 #include <thread>
37 #endif
38 
39 #define _DARWIN_C_SOURCE
40 #include <sys/mman.h>
41 
42 #ifndef MAP_ANONYMOUS
43     #define MAP_ANONYMOUS MAP_ANON
44 #endif
45 
46 #ifndef MAP_STACK
47     #define MAP_STACK (0)
48 #endif
49 
50 #include <Platform/Common/MTThread.h>
51 #include <MTAllocator.h>
52 
53 namespace MT
54 {
55 	class _Fiber;
56 
57 	class Thread : public ThreadBase
58 	{
59 		pthread_t thread;
60 		pthread_attr_t threadAttr;
61 
62 		Memory::StackDesc stackDesc;
63 
64     size_t stackSize;
65 
66 		bool isStarted;
67 
68 		static void* ThreadFuncInternal(void* pThread)
69 		{
70 			Thread* self = (Thread *)pThread;
71 			self->func(self->funcData);
72 			return nullptr;
73 		}
74 
75 	public:
76 
77 		Thread()
78 			: stackSize(0)
79 			, isStarted(false)
80 		{
81 		}
82 
83 		void* GetStackBottom()
84 		{
85 			return stackDesc.stackBottom;
86 		}
87 
88 		size_t GetStackSize()
89 		{
90 			return stackSize;
91 		}
92 
93 
94 		void Start(size_t _stackSize, TThreadEntryPoint entryPoint, void* userData)
95 		{
96 			MT_ASSERT(!isStarted, "Thread already stared");
97 
98 			MT_ASSERT(func == nullptr, "Thread already started");
99 
100 			func = entryPoint;
101 			funcData = userData;
102 
103 			stackDesc = Memory::AllocStack(_stackSize);
104 			stackSize = stackDesc.GetStackSize();
105 
106 			MT_ASSERT(stackSize >= PTHREAD_STACK_MIN, "Thread stack to small");
107 
108 			int err = pthread_attr_init(&threadAttr);
109 			MT_ASSERT(err == 0, "pthread_attr_init - error");
110 
111 			err = pthread_attr_setstack(&threadAttr, stackDesc.stackBottom, stackSize);
112 			MT_ASSERT(err == 0, "pthread_attr_setstack - error");
113 
114 			err = pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_JOINABLE);
115 			MT_ASSERT(err == 0, "pthread_attr_setdetachstate - error");
116 
117 			isStarted = true;
118 
119 			err = pthread_create(&thread, &threadAttr, ThreadFuncInternal, this);
120 			MT_ASSERT(err == 0, "pthread_create - error");
121 		}
122 
123 		void Stop()
124 		{
125 			MT_ASSERT(isStarted, "Thread is not started");
126 
127 			if (func == nullptr)
128 			{
129 				return;
130 			}
131 
132 			void *threadStatus = nullptr;
133 			int err = pthread_join(thread, &threadStatus);
134 			MT_ASSERT(err == 0, "pthread_join - error");
135 
136 			err = pthread_attr_destroy(&threadAttr);
137 			MT_ASSERT(err == 0, "pthread_attr_destroy - error");
138 
139 			func = nullptr;
140 			funcData = nullptr;
141 
142 			if (stackDesc.stackMemory != nullptr)
143 			{
144 				Memory::FreeStack(stackDesc);
145 			}
146 
147 			stackSize = 0;
148 			isStarted = false;
149 		}
150 
151 		bool IsCurrentThread() const
152 		{
153 			if(!isStarted)
154 			{
155 				return false;
156 			}
157 
158 			pthread_t callThread = pthread_self();
159 			if (pthread_equal(callThread, thread))
160 			{
161 					return true;
162 			}
163 			return false;
164 		}
165 
166 		static int GetNumberOfHardwareThreads()
167 		{
168 #ifdef __APPLE_CC__
169             return std::thread::hardware_concurrency();
170 #else
171 			long numberOfProcessors = sysconf( _SC_NPROCESSORS_ONLN );
172 			return (int)numberOfProcessors;
173 #endif
174 		}
175 
176 		static void Sleep(uint32 milliseconds)
177 		{
178 			struct timespec req;
179 			time_t sec = (int)(milliseconds/1000);
180 			milliseconds = milliseconds - (sec*1000);
181 			req.tv_sec = sec;
182 			req.tv_nsec = milliseconds * 1000000L;
183 			while (nanosleep(&req,&req) == -1 )
184 			{
185 				continue;
186 			}
187 		}
188 
189 	};
190 
191 
192 }
193 
194 
195 #endif