1 ///////////////////////////////////////////////////////////////////////////////
4 /// \brief Some threading related helper macros and functions
6 // Author: Lasse Collin
8 // This file has been put into the public domain.
9 // You can do whatever you want with this file.
11 ///////////////////////////////////////////////////////////////////////////////
17 #define _POSIX_C_SOURCE 1
19 // If any type of threading is enabled, #define MYTHREAD_ENABLED.
20 #if defined(MYTHREAD_POSIX) || defined(MYTHREAD_WIN95) \
21 || defined(MYTHREAD_VISTA)
22 # define MYTHREAD_ENABLED 1
26 #ifdef MYTHREAD_ENABLED
28 ////////////////////////////////////////
29 // Shared between all threading types //
30 ////////////////////////////////////////
32 // Locks a mutex for a duration of a block.
34 // Perform mythread_mutex_lock(&mutex) in the beginning of a block
35 // and mythread_mutex_unlock(&mutex) at the end of the block. "break"
36 // may be used to unlock the mutex and jump out of the block.
37 // mythread_sync blocks may be nested.
41 // mythread_sync(mutex) {
44 // break; // Skips bar()
48 // At least GCC optimizes the loops completely away so it doesn't slow
49 // things down at all compared to plain mythread_mutex_lock(&mutex)
50 // and mythread_mutex_unlock(&mutex) calls.
52 #define mythread_sync(mutex) mythread_sync_helper1(mutex, __LINE__)
53 #define mythread_sync_helper1(mutex, line) mythread_sync_helper2(mutex, line)
54 #define mythread_sync_helper2(mutex, line) \
55 for (unsigned int mythread_i_ ## line = 0; \
57 ? (mythread_mutex_unlock(&(mutex)), 0) \
58 : (mythread_mutex_lock(&(mutex)), 1); \
59 mythread_i_ ## line = 1) \
60 for (unsigned int mythread_j_ ## line = 0; \
61 !mythread_j_ ## line; \
62 mythread_j_ ## line = 1)
66 #if !defined(MYTHREAD_ENABLED)
72 // Calls the given function once. This isn't thread safe.
73 #define mythread_once(func) \
75 static bool once_ = false; \
83 #if !(defined(_WIN32) && !defined(__CYGWIN__))
84 // Use sigprocmask() to set the signal mask in single-threaded programs.
88 mythread_sigmask(int how, const sigset_t *restrict set,
89 sigset_t *restrict oset)
91 int ret = sigprocmask(how, set, oset);
98 #elif defined(MYTHREAD_POSIX)
104 #include <sys/time.h>
110 #define MYTHREAD_RET_TYPE void *
111 #define MYTHREAD_RET_VALUE NULL
113 typedef pthread_t mythread;
114 typedef pthread_mutex_t mythread_mutex;
118 #ifdef HAVE_CLOCK_GETTIME
119 // Clock ID (CLOCK_REALTIME or CLOCK_MONOTONIC) associated with
120 // the condition variable.
125 typedef struct timespec mythread_condtime;
128 // Calls the given function once in a thread-safe way.
129 #define mythread_once(func) \
131 static pthread_once_t once_ = PTHREAD_ONCE_INIT; \
132 pthread_once(&once_, &func); \
136 // Use pthread_sigmask() to set the signal mask in multi-threaded programs.
137 // Do nothing on OpenVMS since it lacks pthread_sigmask().
139 mythread_sigmask(int how, const sigset_t *restrict set,
140 sigset_t *restrict oset)
147 int ret = pthread_sigmask(how, set, oset);
154 // Creates a new thread with all signals blocked. Returns zero on success
155 // and non-zero on error.
157 mythread_create(mythread *thread, void *(*func)(void *arg), void *arg)
163 mythread_sigmask(SIG_SETMASK, &all, &old);
164 const int ret = pthread_create(thread, NULL, func, arg);
165 mythread_sigmask(SIG_SETMASK, &old, NULL);
170 // Joins a thread. Returns zero on success and non-zero on error.
172 mythread_join(mythread thread)
174 return pthread_join(thread, NULL);
178 // Initiatlizes a mutex. Returns zero on success and non-zero on error.
180 mythread_mutex_init(mythread_mutex *mutex)
182 return pthread_mutex_init(mutex, NULL);
186 mythread_mutex_destroy(mythread_mutex *mutex)
188 int ret = pthread_mutex_destroy(mutex);
194 mythread_mutex_lock(mythread_mutex *mutex)
196 int ret = pthread_mutex_lock(mutex);
202 mythread_mutex_unlock(mythread_mutex *mutex)
204 int ret = pthread_mutex_unlock(mutex);
210 // Initializes a condition variable.
212 // Using CLOCK_MONOTONIC instead of the default CLOCK_REALTIME makes the
213 // timeout in pthread_cond_timedwait() work correctly also if system time
214 // is suddenly changed. Unfortunately CLOCK_MONOTONIC isn't available
215 // everywhere while the default CLOCK_REALTIME is, so the default is
216 // used if CLOCK_MONOTONIC isn't available.
218 // If clock_gettime() isn't available at all, gettimeofday() will be used.
220 mythread_cond_init(mythread_cond *mycond)
222 #ifdef HAVE_CLOCK_GETTIME
223 // NOTE: HAVE_DECL_CLOCK_MONOTONIC is always defined to 0 or 1.
224 # if defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && HAVE_DECL_CLOCK_MONOTONIC
226 pthread_condattr_t condattr;
228 // POSIX doesn't seem to *require* that pthread_condattr_setclock()
229 // will fail if given an unsupported clock ID. Test that
230 // CLOCK_MONOTONIC really is supported using clock_gettime().
231 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0
232 && pthread_condattr_init(&condattr) == 0) {
233 int ret = pthread_condattr_setclock(
234 &condattr, CLOCK_MONOTONIC);
236 ret = pthread_cond_init(&mycond->cond, &condattr);
238 pthread_condattr_destroy(&condattr);
241 mycond->clk_id = CLOCK_MONOTONIC;
246 // If anything above fails, fall back to the default CLOCK_REALTIME.
247 // POSIX requires that all implementations of clock_gettime() must
248 // support at least CLOCK_REALTIME.
251 mycond->clk_id = CLOCK_REALTIME;
254 return pthread_cond_init(&mycond->cond, NULL);
258 mythread_cond_destroy(mythread_cond *cond)
260 int ret = pthread_cond_destroy(&cond->cond);
266 mythread_cond_signal(mythread_cond *cond)
268 int ret = pthread_cond_signal(&cond->cond);
274 mythread_cond_wait(mythread_cond *cond, mythread_mutex *mutex)
276 int ret = pthread_cond_wait(&cond->cond, mutex);
281 // Waits on a condition or until a timeout expires. If the timeout expires,
282 // non-zero is returned, otherwise zero is returned.
284 mythread_cond_timedwait(mythread_cond *cond, mythread_mutex *mutex,
285 const mythread_condtime *condtime)
287 int ret = pthread_cond_timedwait(&cond->cond, mutex, condtime);
288 assert(ret == 0 || ret == ETIMEDOUT);
292 // Sets condtime to the absolute time that is timeout_ms milliseconds
293 // in the future. The type of the clock to use is taken from cond.
295 mythread_condtime_set(mythread_condtime *condtime, const mythread_cond *cond,
298 condtime->tv_sec = timeout_ms / 1000;
299 condtime->tv_nsec = (timeout_ms % 1000) * 1000000;
301 #ifdef HAVE_CLOCK_GETTIME
303 int ret = clock_gettime(cond->clk_id, &now);
307 condtime->tv_sec += now.tv_sec;
308 condtime->tv_nsec += now.tv_nsec;
313 gettimeofday(&now, NULL);
315 condtime->tv_sec += now.tv_sec;
316 condtime->tv_nsec += now.tv_usec * 1000L;
319 // tv_nsec must stay in the range [0, 999_999_999].
320 if (condtime->tv_nsec >= 1000000000L) {
321 condtime->tv_nsec -= 1000000000L;
327 #elif defined(MYTHREAD_WIN95) || defined(MYTHREAD_VISTA)
329 /////////////////////
330 // Windows threads //
331 /////////////////////
333 #define WIN32_LEAN_AND_MEAN
334 #ifdef MYTHREAD_VISTA
336 # define _WIN32_WINNT 0x0600
341 #define MYTHREAD_RET_TYPE unsigned int __stdcall
342 #define MYTHREAD_RET_VALUE 0
344 typedef HANDLE mythread;
345 typedef CRITICAL_SECTION mythread_mutex;
347 #ifdef MYTHREAD_WIN95
348 typedef HANDLE mythread_cond;
350 typedef CONDITION_VARIABLE mythread_cond;
354 // Tick count (milliseconds) in the beginning of the timeout.
355 // NOTE: This is 32 bits so it wraps around after 49.7 days.
356 // Multi-day timeouts may not work as expected.
359 // Length of the timeout in milliseconds. The timeout expires
360 // when the current tick count minus "start" is equal or greater
366 // mythread_once() is only available with Vista threads.
367 #ifdef MYTHREAD_VISTA
368 #define mythread_once(func) \
370 static INIT_ONCE once_ = INIT_ONCE_STATIC_INIT; \
372 if (!InitOnceBeginInitialize(&once_, 0, &pending_, NULL)) \
376 if (!InitOnceComplete(&once, 0, NULL)) \
382 // mythread_sigmask() isn't available on Windows. Even a dummy version would
383 // make no sense because the other POSIX signal functions are missing anyway.
387 mythread_create(mythread *thread,
388 unsigned int (__stdcall *func)(void *arg), void *arg)
390 uintptr_t ret = _beginthreadex(NULL, 0, func, arg, 0, NULL);
394 *thread = (HANDLE)ret;
399 mythread_join(mythread thread)
403 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0)
406 if (!CloseHandle(thread))
414 mythread_mutex_init(mythread_mutex *mutex)
416 InitializeCriticalSection(mutex);
421 mythread_mutex_destroy(mythread_mutex *mutex)
423 DeleteCriticalSection(mutex);
427 mythread_mutex_lock(mythread_mutex *mutex)
429 EnterCriticalSection(mutex);
433 mythread_mutex_unlock(mythread_mutex *mutex)
435 LeaveCriticalSection(mutex);
440 mythread_cond_init(mythread_cond *cond)
442 #ifdef MYTHREAD_WIN95
443 *cond = CreateEvent(NULL, FALSE, FALSE, NULL);
444 return *cond == NULL ? -1 : 0;
446 InitializeConditionVariable(cond);
452 mythread_cond_destroy(mythread_cond *cond)
454 #ifdef MYTHREAD_WIN95
462 mythread_cond_signal(mythread_cond *cond)
464 #ifdef MYTHREAD_WIN95
467 WakeConditionVariable(cond);
472 mythread_cond_wait(mythread_cond *cond, mythread_mutex *mutex)
474 #ifdef MYTHREAD_WIN95
475 LeaveCriticalSection(mutex);
476 WaitForSingleObject(*cond, INFINITE);
477 EnterCriticalSection(mutex);
479 BOOL ret = SleepConditionVariableCS(cond, mutex, INFINITE);
486 mythread_cond_timedwait(mythread_cond *cond, mythread_mutex *mutex,
487 const mythread_condtime *condtime)
489 #ifdef MYTHREAD_WIN95
490 LeaveCriticalSection(mutex);
493 DWORD elapsed = GetTickCount() - condtime->start;
494 DWORD timeout = elapsed >= condtime->timeout
495 ? 0 : condtime->timeout - elapsed;
497 #ifdef MYTHREAD_WIN95
498 DWORD ret = WaitForSingleObject(*cond, timeout);
499 assert(ret == WAIT_OBJECT_0 || ret == WAIT_TIMEOUT);
501 EnterCriticalSection(mutex);
503 return ret == WAIT_TIMEOUT;
505 BOOL ret = SleepConditionVariableCS(cond, mutex, timeout);
506 assert(ret || GetLastError() == ERROR_TIMEOUT);
512 mythread_condtime_set(mythread_condtime *condtime, const mythread_cond *cond,
516 condtime->start = GetTickCount();
517 condtime->timeout = timeout;