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"
30 #if __cplusplus >= 201103L
33 #define UNUSED(expr) do { (void)(expr); } while (0)
44 // For getNumberOfProcessors
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>
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 #elif defined(__APPLE__)
82 #include <mach/mach_init.h>
83 #include <mach/thread_act.h>
87 Thread::Thread(const std::string &name) :
92 #if __cplusplus >= 201103L
94 #elif !defined(_WIN32)
102 #if __cplusplus >= 201103L
103 if (!thread || !thread->joinable())
106 #elif defined(_WIN32)
109 WaitForSingleObject(thread, INFINITE);
114 int ret = pthread_join(thread, &status);
126 request_stop = false;
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);
134 thread = CreateThread(NULL, 0, theThread, this, 0, &thread_id);
136 thread = (HANDLE)_beginthreadex(NULL, 0, theThread, this, 0, &thread_id);
143 MutexAutoLock l(continue_mutex);
145 status = pthread_create(&thread, NULL, theThread, this);
151 #if __cplusplus < 201103L
152 // Wait until running
158 struct timespec req, rem;
160 req.tv_nsec = 1000000;
161 nanosleep(&req, &rem);
175 TerminateThread(getThreadHandle(), 0);
176 CloseHandle(getThreadHandle());
183 pthread_kill(getThreadHandle(), SIGKILL);
185 pthread_cancel(getThreadHandle());
189 #if __cplusplus >= 201103L
197 bool Thread::isSameThread()
199 #if __cplusplus >= 201103L
200 return thread->get_id() == std::this_thread::get_id();
201 #elif defined(_WIN32)
202 return GetCurrentThreadId() == thread_id;
204 return pthread_equal(pthread_self(), thread);
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)
216 void *Thread::theThread(void *param)
219 #if __cplusplus < 201103L
220 Thread *th = static_cast<Thread *>(param);
225 log_register_thread(th->name);
227 th->retval = th->run();
229 log_deregister_thread();
232 #if __cplusplus < 201103L
234 CloseHandle(th->thread);
241 void Thread::setName(const std::string &name)
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.
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;
264 RaiseException(0x406D1388, 0, sizeof(info) / sizeof(DWORD), (ULONG_PTR *)&info);
265 } __except (EXCEPTION_CONTINUE_EXECUTION) {
267 #elif defined(_WIN32) || defined(__GNU__)
268 // These platforms are known to not support thread names.
269 // Silently ignore the request.
271 #warning "Unrecognized platform, thread names will not be available."
276 unsigned int Thread::getNumberOfProcessors()
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;
285 return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
286 #elif defined(_GNU_SOURCE)
288 #elif defined(_WIN32)
290 GetSystemInfo(&sysinfo);
291 return sysinfo.dwNumberOfProcessors;
292 #elif defined(PTW32_VERSION) || defined(__hpux)
293 return pthread_num_processors_np();
300 bool Thread::bindToProcessor(unsigned int num)
302 #if defined(__ANDROID__)
304 #elif defined(_WIN32)
305 return SetThreadAffinityMask(getThreadHandle(), 1 << num);
306 #elif __FreeBSD_version >= 702106 || defined(__linux) || defined(linux)
309 CPU_SET(num, &cpuset);
310 return pthread_setaffinity_np(getThreadHandle(), sizeof(cpuset),
312 #elif defined(__sun) || defined(sun)
313 return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(getThreadHandle()),
316 return bindprocessor(BINDTHREAD, (tid_t) getThreadHandle(), pnumber) == 0;
317 #elif defined(__hpux) || defined(hpux)
318 pthread_spu_t answer;
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;
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;
336 bool Thread::setPriority(int prio)
339 return SetThreadPriority(getThreadHandle(), prio);
341 struct sched_param sparam;
344 if (pthread_getschedparam(getThreadHandle(), &policy, &sparam) != 0)
347 int min = sched_get_priority_min(policy);
348 int max = sched_get_priority_max(policy);
350 sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
351 return pthread_setschedparam(getThreadHandle(), policy, &sparam) == 0;