2 This file is a part of the JThread package, which contains some object-
3 oriented thread wrappers for different thread implementations.
5 Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com)
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:
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
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.
26 #include "threading/thread.h"
27 #include "threading/mutex_auto_lock.h"
31 #define UNUSED(expr) do { (void)(expr); } while (0)
35 #include <system_error>
40 #elif USE_POSIX_THREADS
47 #if defined(__FreeBSD__) || defined(__APPLE__)
48 #include <sys/types.h>
49 #include <sys/sysctl.h>
50 #elif defined(_GNU_SOURCE)
51 #include <sys/sysinfo.h>
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
70 // for bindToProcessor
71 #if __FreeBSD_version >= 702106
72 typedef cpuset_t cpu_set_t;
73 #elif defined(__linux) || defined(linux)
75 #elif defined(__sun) || defined(sun)
76 #include <sys/types.h>
77 #include <sys/processor.h>
78 #include <sys/procset.h>
80 #include <sys/processor.h>
81 #include <sys/thread.h>
82 #elif defined(__APPLE__)
83 #include <mach/mach_init.h>
84 #include <mach/thread_act.h>
88 Thread::Thread(const std::string &name) :
91 m_request_stop(false),
95 m_kernel_thread_id = -1;
112 MutexAutoLock lock(m_continue_mutex);
119 #if USE_CPP11_THREADS
122 m_thread_obj = new std::thread(threadProc, this);
123 m_thread_id = m_thread->get_id();
124 m_thread_handle = m_thread->native_handle();
125 } except (const std::system_error &e) {
129 #elif USE_WIN_THREADS
131 m_thread_handle = CreateThread(NULL, 0, threadProc, this, 0, &m_thread_id);
132 if (!m_thread_handle)
135 #elif USE_POSIX_THREADS
137 int status = pthread_create(&m_thread_handle, NULL, threadProc, this);
141 m_thread_id = m_thread_handle;
154 m_request_stop = true;
164 #if USE_CPP11_THREADS
166 m_thread_obj->join();
168 #elif USE_WIN_THREADS
170 int ret = WaitForSingleObject(m_thread_handle, INFINITE);
171 assert(ret == WAIT_OBJECT_0);
174 #elif USE_POSIX_THREADS
176 int ret = pthread_join(m_thread_handle, NULL);
182 assert(m_running == false);
196 TerminateThread(m_thread_handle, 0);
199 // We need to pthread_kill instead on Android since NDKv5's pthread
200 // implementation is incomplete.
202 pthread_kill(m_thread_handle, SIGKILL);
204 pthread_cancel(m_thread_handle);
216 void Thread::cleanup()
218 #if USE_CPP11_THREADS
223 #elif USE_WIN_THREADS
225 CloseHandle(m_thread_handle);
226 m_thread_handle = NULL;
229 #elif USE_POSIX_THREADS
231 // Can't do any cleanup for pthreads
238 m_request_stop = false;
242 bool Thread::getReturnValue(void **ret)
252 bool Thread::isCurrentThread()
254 return thr_is_current_thread(m_thread_id);
258 #if USE_CPP11_THREADS || USE_POSIX_THREADS
259 void *(Thread::threadProc)(void *param)
260 #elif defined(_WIN32_WCE)
261 DWORD (Thread::threadProc)(LPVOID param)
262 #elif defined(_WIN32)
263 DWORD WINAPI (Thread::threadProc)(LPVOID param)
266 Thread *thr = (Thread *)param;
269 m_kernel_thread_id = thread_self();
272 thr->setName(thr->m_name);
274 g_logger.registerThread(thr->m_name);
275 thr->m_running = true;
277 thr->m_retval = thr->run();
279 thr->m_running = false;
280 g_logger.deregisterThread();
286 void Thread::setName(const std::string &name)
288 #if defined(linux) || defined(__linux)
290 // It would be cleaner to do this with pthread_setname_np,
291 // which was added to glibc in version 2.12, but some major
292 // distributions are still runing 2.11 and previous versions.
293 prctl(PR_SET_NAME, name.c_str());
295 #elif defined(__FreeBSD__) || defined(__OpenBSD__)
297 pthread_set_name_np(pthread_self(), name.c_str());
299 #elif defined(__NetBSD__)
301 pthread_setname_np(pthread_self(), name.c_str());
303 #elif defined(__APPLE__)
305 pthread_setname_np(name.c_str());
307 #elif defined(_MSC_VER)
309 // Windows itself doesn't support thread names,
310 // but the MSVC debugger does...
311 THREADNAME_INFO info;
313 info.dwType = 0x1000;
314 info.szName = name.c_str();
315 info.dwThreadID = -1;
319 RaiseException(0x406D1388, 0,
320 sizeof(info) / sizeof(DWORD), (ULONG_PTR *)&info);
321 } __except (EXCEPTION_CONTINUE_EXECUTION) {
324 #elif defined(_WIN32) || defined(__GNU__)
326 // These platforms are known to not support thread names.
327 // Silently ignore the request.
330 #warning "Unrecognized platform, thread names will not be available."
335 unsigned int Thread::getNumberOfProcessors()
337 #if __cplusplus >= 201103L
339 return std::thread::hardware_concurrency();
341 #elif defined(_SC_NPROCESSORS_ONLN)
343 return sysconf(_SC_NPROCESSORS_ONLN);
345 #elif defined(__FreeBSD__) || defined(__NetBSD__) || \
346 defined(__DragonFly__) || defined(__APPLE__)
348 unsigned int num_cpus = 1;
349 size_t len = sizeof(num_cpus);
355 sysctl(mib, 2, &num_cpus, &len, NULL, 0);
358 #elif defined(_GNU_SOURCE)
362 #elif defined(_WIN32)
365 GetSystemInfo(&sysinfo);
366 return sysinfo.dwNumberOfProcessors;
368 #elif defined(PTW32_VERSION) || defined(__hpux)
370 return pthread_num_processors_np();
380 bool Thread::bindToProcessor(unsigned int proc_number)
382 #if defined(__ANDROID__)
386 #elif defined(_WIN32)
388 return SetThreadAffinityMask(m_thread_handle, 1 << proc_number);
390 #elif __FreeBSD_version >= 702106 || defined(__linux) || defined(linux)
395 CPU_SET(proc_number, &cpuset);
397 return pthread_setaffinity_np(m_thread_handle, sizeof(cpuset), &cpuset) == 0;
399 #elif defined(__sun) || defined(sun)
401 return processor_bind(P_LWPID, P_MYID, proc_number, NULL) == 0
405 return bindprocessor(BINDTHREAD, m_kernel_thread_id, proc_number) == 0;
407 #elif defined(__hpux) || defined(hpux)
409 pthread_spu_t answer;
411 return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
412 &answer, proc_number, m_thread_handle) == 0;
414 #elif defined(__APPLE__)
416 struct thread_affinity_policy tapol;
418 thread_port_t threadport = pthread_mach_thread_np(m_thread_handle);
419 tapol.affinity_tag = proc_number + 1;
420 return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
421 (thread_policy_t)&tapol,
422 THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
432 bool Thread::setPriority(int prio)
436 return SetThreadPriority(m_thread_handle, prio);
440 struct sched_param sparam;
443 if (pthread_getschedparam(m_thread_handle, &policy, &sparam) != 0)
446 int min = sched_get_priority_min(policy);
447 int max = sched_get_priority_max(policy);
449 sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
450 return pthread_setschedparam(m_thread_handle, policy, &sparam) == 0;