]> git.lizzy.rs Git - minetest.git/blob - src/threading/thread.cpp
C++11 patchset 5: use std::threads and remove old compat layer (#5928)
[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 #include "porting.h"
30
31 // for setName
32 #if defined(__linux__)
33         #include <sys/prctl.h>
34 #elif defined(__FreeBSD__) || defined(__OpenBSD__)
35         #include <pthread_np.h>
36 #elif defined(_MSC_VER)
37         struct THREADNAME_INFO {
38                 DWORD dwType;     // Must be 0x1000
39                 LPCSTR szName;    // Pointer to name (in user addr space)
40                 DWORD dwThreadID; // Thread ID (-1=caller thread)
41                 DWORD dwFlags;    // Reserved for future use, must be zero
42         };
43 #endif
44
45 // for bindToProcessor
46 #if __FreeBSD_version >= 702106
47         typedef cpuset_t cpu_set_t;
48 #elif defined(__sun) || defined(sun)
49         #include <sys/types.h>
50         #include <sys/processor.h>
51         #include <sys/procset.h>
52 #elif defined(_AIX)
53         #include <sys/processor.h>
54         #include <sys/thread.h>
55 #elif defined(__APPLE__)
56         #include <mach/mach_init.h>
57         #include <mach/thread_act.h>
58 #endif
59
60
61 Thread::Thread(const std::string &name) :
62         m_name(name),
63         m_retval(NULL),
64         m_joinable(false),
65         m_request_stop(false),
66         m_running(false)
67 {
68 #ifdef _AIX
69         m_kernel_thread_id = -1;
70 #endif
71 }
72
73
74 Thread::~Thread()
75 {
76         kill();
77
78         // Make sure start finished mutex is unlocked before it's destroyed
79         m_start_finished_mutex.try_lock();
80         m_start_finished_mutex.unlock();
81
82 }
83
84
85 bool Thread::start()
86 {
87         MutexAutoLock lock(m_mutex);
88
89         if (m_running)
90                 return false;
91
92         m_request_stop = false;
93
94         // The mutex may already be locked if the thread is being restarted
95         m_start_finished_mutex.try_lock();
96
97         try {
98                 m_thread_obj = new std::thread(threadProc, this);
99         } catch (const std::system_error &e) {
100                 return false;
101         }
102
103         // Allow spawned thread to continue
104         m_start_finished_mutex.unlock();
105
106         while (!m_running)
107                 sleep_ms(1);
108
109         m_joinable = true;
110
111         return true;
112 }
113
114
115 bool Thread::stop()
116 {
117         m_request_stop = true;
118         return true;
119 }
120
121
122 bool Thread::wait()
123 {
124         MutexAutoLock lock(m_mutex);
125
126         if (!m_joinable)
127                 return false;
128
129
130         m_thread_obj->join();
131
132         delete m_thread_obj;
133         m_thread_obj = NULL;
134
135         assert(m_running == false);
136         m_joinable = false;
137         return true;
138 }
139
140
141 bool Thread::kill()
142 {
143         if (!m_running) {
144                 wait();
145                 return false;
146         }
147
148         m_running = false;
149
150 #if defined(_WIN32)
151         // See https://msdn.microsoft.com/en-us/library/hh920601.aspx#thread__native_handle_method
152         TerminateThread((HANDLE) m_thread_obj->native_handle(), 0);
153         CloseHandle((HANDLE) m_thread_obj->native_handle());
154 #else
155         // We need to pthread_kill instead on Android since NDKv5's pthread
156         // implementation is incomplete.
157 # ifdef __ANDROID__
158         pthread_kill(getThreadHandle(), SIGKILL);
159 # else
160         pthread_cancel(getThreadHandle());
161 # endif
162         wait();
163 #endif
164
165         m_retval       = NULL;
166         m_joinable     = false;
167         m_request_stop = false;
168
169         return true;
170 }
171
172
173 bool Thread::getReturnValue(void **ret)
174 {
175         if (m_running)
176                 return false;
177
178         *ret = m_retval;
179         return true;
180 }
181
182
183 void *Thread::threadProc(void *param)
184 {
185         Thread *thr = (Thread *)param;
186
187 #ifdef _AIX
188         thr->m_kernel_thread_id = thread_self();
189 #endif
190
191         thr->setName(thr->m_name);
192
193         g_logger.registerThread(thr->m_name);
194         thr->m_running = true;
195
196         // Wait for the thread that started this one to finish initializing the
197         // thread handle so that getThreadId/getThreadHandle will work.
198         thr->m_start_finished_mutex.lock();
199
200         thr->m_retval = thr->run();
201
202         thr->m_running = false;
203         g_logger.deregisterThread();
204
205         // 0 is returned here to avoid an unnecessary ifdef clause
206         return 0;
207 }
208
209
210 void Thread::setName(const std::string &name)
211 {
212 #if defined(__linux__)
213
214         // It would be cleaner to do this with pthread_setname_np,
215         // which was added to glibc in version 2.12, but some major
216         // distributions are still runing 2.11 and previous versions.
217         prctl(PR_SET_NAME, name.c_str());
218
219 #elif defined(__FreeBSD__) || defined(__OpenBSD__)
220
221         pthread_set_name_np(pthread_self(), name.c_str());
222
223 #elif defined(__NetBSD__)
224
225         pthread_setname_np(pthread_self(), name.c_str());
226
227 #elif defined(__APPLE__)
228
229         pthread_setname_np(name.c_str());
230
231 #elif defined(_MSC_VER)
232
233         // Windows itself doesn't support thread names,
234         // but the MSVC debugger does...
235         THREADNAME_INFO info;
236
237         info.dwType = 0x1000;
238         info.szName = name.c_str();
239         info.dwThreadID = -1;
240         info.dwFlags = 0;
241
242         __try {
243                 RaiseException(0x406D1388, 0,
244                         sizeof(info) / sizeof(DWORD), (ULONG_PTR *)&info);
245         } __except (EXCEPTION_CONTINUE_EXECUTION) {
246         }
247
248 #elif defined(_WIN32) || defined(__GNU__)
249
250         // These platforms are known to not support thread names.
251         // Silently ignore the request.
252
253 #else
254         #warning "Unrecognized platform, thread names will not be available."
255 #endif
256 }
257
258
259 unsigned int Thread::getNumberOfProcessors()
260 {
261         return std::thread::hardware_concurrency();
262 }
263
264
265 bool Thread::bindToProcessor(unsigned int proc_number)
266 {
267 #if defined(__ANDROID__)
268
269         return false;
270
271 #elif USE_WIN_THREADS
272
273         return SetThreadAffinityMask(getThreadHandle(), 1 << proc_number);
274
275 #elif __FreeBSD_version >= 702106 || defined(__linux__)
276
277         cpu_set_t cpuset;
278
279         CPU_ZERO(&cpuset);
280         CPU_SET(proc_number, &cpuset);
281
282         return pthread_setaffinity_np(getThreadHandle(), sizeof(cpuset), &cpuset) == 0;
283
284 #elif defined(__sun) || defined(sun)
285
286         return processor_bind(P_LWPID, P_MYID, proc_number, NULL) == 0
287
288 #elif defined(_AIX)
289
290         return bindprocessor(BINDTHREAD, m_kernel_thread_id, proc_number) == 0;
291
292 #elif defined(__hpux) || defined(hpux)
293
294         pthread_spu_t answer;
295
296         return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
297                         &answer, proc_number, getThreadHandle()) == 0;
298
299 #elif defined(__APPLE__)
300
301         struct thread_affinity_policy tapol;
302
303         thread_port_t threadport = pthread_mach_thread_np(getThreadHandle());
304         tapol.affinity_tag = proc_number + 1;
305         return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
306                         (thread_policy_t)&tapol,
307                         THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
308
309 #else
310
311         return false;
312
313 #endif
314 }
315
316
317 bool Thread::setPriority(int prio)
318 {
319 #if USE_WIN_THREADS
320
321         return SetThreadPriority(getThreadHandle(), prio);
322
323 #else
324
325         struct sched_param sparam;
326         int policy;
327
328         if (pthread_getschedparam(getThreadHandle(), &policy, &sparam) != 0)
329                 return false;
330
331         int min = sched_get_priority_min(policy);
332         int max = sched_get_priority_max(policy);
333
334         sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
335         return pthread_setschedparam(getThreadHandle(), policy, &sparam) == 0;
336
337 #endif
338 }
339