]> git.lizzy.rs Git - minetest.git/blob - src/threading/thread.cpp
Fix MinGW 32-bit build
[minetest.git] / src / threading / thread.cpp
1 /*
2 This file is a part of the JThread package, which contains some object-
3 oriented thread wrappers for different thread implementations.
4
5 Copyright (c) 2000-2006  Jori Liesenborgs (jori.liesenborgs@gmail.com)
6
7 Permission is hereby granted, free of charge, to any person obtaining a
8 copy of this software and associated documentation files (the "Software"),
9 to deal in the Software without restriction, including without limitation
10 the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 and/or sell copies of the Software, and to permit persons to whom the
12 Software is furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23 DEALINGS IN THE SOFTWARE.
24 */
25
26 #include "threading/thread.h"
27 #include "threading/mutex_auto_lock.h"
28 #include "log.h"
29
30 #if __cplusplus >= 201103L
31         #include <chrono>
32 #else
33         #define UNUSED(expr) do { (void)(expr); } while (0)
34 # ifdef _WIN32
35 #  ifndef _WIN32_WCE
36         #include <process.h>
37 #  endif
38 # else
39         #include <ctime>
40         #include <cassert>
41         #include <cstdlib>
42         #include <sys/time.h>
43
44         // For getNumberOfProcessors
45         #include <unistd.h>
46 #  if defined(__FreeBSD__) || defined(__APPLE__)
47         #include <sys/types.h>
48         #include <sys/sysctl.h>
49 #  elif defined(_GNU_SOURCE)
50         #include <sys/sysinfo.h>
51 #  endif
52 # endif
53 #endif
54
55
56 // For setName
57 #if defined(linux) || defined(__linux)
58         #include <sys/prctl.h>
59 #elif defined(__FreeBSD__) || defined(__OpenBSD__)
60         #include <pthread_np.h>
61 #elif defined(_MSC_VER)
62         struct THREADNAME_INFO {
63                 DWORD dwType; // Must be 0x1000
64                 LPCSTR szName; // Pointer to name (in user addr space)
65                 DWORD dwThreadID; // Thread ID (-1=caller thread)
66                 DWORD dwFlags; // Reserved for future use, must be zero
67         };
68 #endif
69
70 // For bindToProcessor
71 #if __FreeBSD_version >= 702106
72         typedef cpuset_t cpu_set_t;
73 #elif defined(__linux) || defined(linux)
74         #include <sched.h>
75 #elif defined(__sun) || defined(sun)
76         #include <sys/types.h>
77         #include <sys/processor.h>
78         #include <sys/procset.h>
79 #elif defined(_AIX)
80         #include <sys/processor.h>
81 #elif defined(__APPLE__)
82         #include <mach/mach_init.h>
83         #include <mach/thread_act.h>
84 #endif
85
86
87 Thread::Thread(const std::string &name) :
88         name(name),
89         retval(NULL),
90         request_stop(false),
91         running(false)
92 #if __cplusplus >= 201103L
93         , thread(NULL)
94 #elif !defined(_WIN32)
95         , started(false)
96 #endif
97 {}
98
99
100 void Thread::wait()
101 {
102 #if __cplusplus >= 201103L
103         if (!thread || !thread->joinable())
104                 return;
105         thread->join();
106 #elif defined(_WIN32)
107         if (!running)
108                 return;
109         WaitForSingleObject(thread, INFINITE);
110 #else // pthread
111         void *status;
112         if (!started)
113                 return;
114         int ret = pthread_join(thread, &status);
115         assert(!ret);
116         UNUSED(ret);
117         started = false;
118 #endif
119 }
120
121
122 bool Thread::start()
123 {
124         if (running)
125                 return false;
126         request_stop = false;
127
128 #if __cplusplus >= 201103L
129         MutexAutoLock l(continue_mutex);
130         thread = new std::thread(theThread, this);
131 #elif defined(_WIN32)
132         MutexAutoLock l(continue_mutex);
133 # ifdef _WIN32_WCE
134         thread = CreateThread(NULL, 0, theThread, this, 0, &thread_id);
135 # else
136         thread = (HANDLE)_beginthreadex(NULL, 0, theThread, this, 0, &thread_id);
137 # endif
138         if (!thread)
139                 return false;
140 #else
141         int status;
142
143         MutexAutoLock l(continue_mutex);
144
145         status = pthread_create(&thread, NULL, theThread, this);
146
147         if (status)
148                 return false;
149 #endif
150
151 #if __cplusplus < 201103L
152         // Wait until running
153         while (!running) {
154 # ifdef _WIN32
155                 Sleep(1);
156         }
157 # else
158                 struct timespec req, rem;
159                 req.tv_sec = 0;
160                 req.tv_nsec = 1000000;
161                 nanosleep(&req, &rem);
162         }
163         started = true;
164 # endif
165 #endif
166         return true;
167 }
168
169
170 bool Thread::kill()
171 {
172 #ifdef _WIN32
173         if (!running)
174                 return false;
175         TerminateThread(getThreadHandle(), 0);
176         CloseHandle(getThreadHandle());
177 #else
178         if (!running) {
179                 wait();
180                 return false;
181         }
182 # ifdef __ANDROID__
183         pthread_kill(getThreadHandle(), SIGKILL);
184 # else
185         pthread_cancel(getThreadHandle());
186 # endif
187         wait();
188 #endif
189 #if __cplusplus >= 201103L
190         delete thread;
191 #endif
192         running = false;
193         return true;
194 }
195
196
197 bool Thread::isSameThread()
198 {
199 #if __cplusplus >= 201103L
200         return thread->get_id() == std::this_thread::get_id();
201 #elif defined(_WIN32)
202         return GetCurrentThreadId() == thread_id;
203 #else
204         return pthread_equal(pthread_self(), thread);
205 #endif
206 }
207
208
209 #if __cplusplus >= 201103L
210 void Thread::theThread(Thread *th)
211 #elif defined(_WIN32_WCE)
212 DWORD WINAPI Thread::theThread(void *param)
213 #elif defined(_WIN32)
214 UINT __stdcall Thread::theThread(void *param)
215 #else
216 void *Thread::theThread(void *param)
217 #endif
218 {
219 #if __cplusplus < 201103L
220         Thread *th = static_cast<Thread *>(param);
221 #endif
222         th->running = true;
223
224         th->setName();
225         log_register_thread(th->name);
226
227         th->retval = th->run();
228
229         log_deregister_thread();
230
231         th->running = false;
232 #if __cplusplus < 201103L
233 # ifdef _WIN32
234         CloseHandle(th->thread);
235 # endif
236         return NULL;
237 #endif
238 }
239
240
241 void Thread::setName(const std::string &name)
242 {
243 #if defined(linux) || defined(__linux)
244         /* It would be cleaner to do this with pthread_setname_np,
245          * which was added to glibc in version 2.12, but some major
246          * distributions are still runing 2.11 and previous versions.
247          */
248         prctl(PR_SET_NAME, name.c_str());
249 #elif defined(__FreeBSD__) || defined(__OpenBSD__)
250         pthread_set_name_np(pthread_self(), name.c_str());
251 #elif defined(__NetBSD__)
252         pthread_setname_np(pthread_self(), name.c_str());
253 #elif defined(__APPLE__)
254         pthread_setname_np(name.c_str());
255 #elif defined(_MSC_VER)
256         // Windows itself doesn't support thread names,
257         // but the MSVC debugger does...
258         THREADNAME_INFO info;
259         info.dwType = 0x1000;
260         info.szName = name.c_str();
261         info.dwThreadID = -1;
262         info.dwFlags = 0;
263         __try {
264                 RaiseException(0x406D1388, 0, sizeof(info) / sizeof(DWORD), (ULONG_PTR *)&info);
265         } __except (EXCEPTION_CONTINUE_EXECUTION) {
266         }
267 #elif defined(_WIN32) || defined(__GNU__)
268         // These platforms are known to not support thread names.
269         // Silently ignore the request.
270 #else
271         #warning "Unrecognized platform, thread names will not be available."
272 #endif
273 }
274
275
276 unsigned int Thread::getNumberOfProcessors()
277 {
278 #if __cplusplus >= 201103L
279         return std::thread::hardware_concurrency();
280 #elif defined(_SC_NPROCESSORS_ONLN)
281         return sysconf(_SC_NPROCESSORS_ONLN);
282 #elif defined(__FreeBSD__) || defined(__APPLE__)
283         unsigned int len, count;
284         len = sizeof(count);
285         return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
286 #elif defined(_GNU_SOURCE)
287         return get_nprocs();
288 #elif defined(_WIN32)
289         SYSTEM_INFO sysinfo;
290         GetSystemInfo(&sysinfo);
291         return sysinfo.dwNumberOfProcessors;
292 #elif defined(PTW32_VERSION) || defined(__hpux)
293         return pthread_num_processors_np();
294 #else
295         return 1;
296 #endif
297 }
298
299
300 bool Thread::bindToProcessor(unsigned int num)
301 {
302 #if defined(__ANDROID__)
303         return false;
304 #elif defined(_WIN32)
305         return SetThreadAffinityMask(getThreadHandle(), 1 << num);
306 #elif __FreeBSD_version >= 702106 || defined(__linux) || defined(linux)
307         cpu_set_t cpuset;
308         CPU_ZERO(&cpuset);
309         CPU_SET(num, &cpuset);
310         return pthread_setaffinity_np(getThreadHandle(), sizeof(cpuset),
311                 &cpuset) == 0;
312 #elif defined(__sun) || defined(sun)
313         return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(getThreadHandle()),
314                         num, NULL) == 0
315 #elif defined(_AIX)
316         return bindprocessor(BINDTHREAD, (tid_t) getThreadHandle(), pnumber) == 0;
317 #elif defined(__hpux) || defined(hpux)
318         pthread_spu_t answer;
319
320         return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
321                         &answer, num, getThreadHandle()) == 0;
322 #elif defined(__APPLE__)
323         struct thread_affinity_policy tapol;
324
325         thread_port_t threadport = pthread_mach_thread_np(getThreadHandle());
326         tapol.affinity_tag = num + 1;
327         return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
328                         (thread_policy_t)&tapol,
329                         THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
330 #else
331         return false;
332 #endif
333 }
334
335
336 bool Thread::setPriority(int prio)
337 {
338 #if defined(_WIN32)
339         return SetThreadPriority(getThreadHandle(), prio);
340 #else
341         struct sched_param sparam;
342         int policy;
343
344         if (pthread_getschedparam(getThreadHandle(), &policy, &sparam) != 0)
345                 return false;
346
347         int min = sched_get_priority_min(policy);
348         int max = sched_get_priority_max(policy);
349
350         sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
351         return pthread_setschedparam(getThreadHandle(), policy, &sparam) == 0;
352 #endif
353 }
354