Move threads.c to a separate source dir
[openal-soft.git] / common / threads.c
blobccbe209feb23f1cbfd6202e0830b0e9c370dba85
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 1999-2007 by authors.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #include "config.h"
23 #include "threads.h"
25 #include <stdlib.h>
26 #include <string.h>
27 #include <errno.h>
29 #include "uintmap.h"
32 extern inline althrd_t althrd_current(void);
33 extern inline int althrd_equal(althrd_t thr0, althrd_t thr1);
34 extern inline void althrd_exit(int res);
35 extern inline void althrd_yield(void);
37 extern inline int almtx_lock(almtx_t *mtx);
38 extern inline int almtx_unlock(almtx_t *mtx);
39 extern inline int almtx_trylock(almtx_t *mtx);
41 extern inline void *altss_get(altss_t tss_id);
42 extern inline int altss_set(altss_t tss_id, void *val);
45 #ifndef UNUSED
46 #if defined(__cplusplus)
47 #define UNUSED(x)
48 #elif defined(__GNUC__)
49 #define UNUSED(x) UNUSED_##x __attribute__((unused))
50 #elif defined(__LCLINT__)
51 #define UNUSED(x) /*@unused@*/ x
52 #else
53 #define UNUSED(x) x
54 #endif
55 #endif
58 #define THREAD_STACK_SIZE (1*1024*1024) /* 1MB */
60 #ifdef _WIN32
62 #define WIN32_LEAN_AND_MEAN
63 #include <windows.h>
64 #include <mmsystem.h>
67 void althrd_setname(althrd_t thr, const char *name)
69 #if defined(_MSC_VER)
70 #define MS_VC_EXCEPTION 0x406D1388
71 #pragma pack(push,8)
72 struct {
73 DWORD dwType; // Must be 0x1000.
74 LPCSTR szName; // Pointer to name (in user addr space).
75 DWORD dwThreadID; // Thread ID (-1=caller thread).
76 DWORD dwFlags; // Reserved for future use, must be zero.
77 } info;
78 #pragma pack(pop)
79 info.dwType = 0x1000;
80 info.szName = name;
81 info.dwThreadID = thr;
82 info.dwFlags = 0;
84 __try {
85 RaiseException(MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info);
87 __except(EXCEPTION_CONTINUE_EXECUTION) {
89 #undef MS_VC_EXCEPTION
90 #else
91 (void)thr;
92 (void)name;
93 #endif
97 static UIntMap ThrdIdHandle = UINTMAP_STATIC_INITIALIZE;
99 static void NTAPI althrd_callback(void* UNUSED(handle), DWORD reason, void* UNUSED(reserved))
101 if(reason == DLL_PROCESS_DETACH)
102 ResetUIntMap(&ThrdIdHandle);
104 #ifdef _MSC_VER
105 #pragma section(".CRT$XLC",read)
106 __declspec(allocate(".CRT$XLC")) PIMAGE_TLS_CALLBACK althrd_callback_ = althrd_callback;
107 #elif defined(__GNUC__)
108 PIMAGE_TLS_CALLBACK althrd_callback_ __attribute__((section(".CRT$XLC"))) = althrd_callback;
109 #else
110 PIMAGE_TLS_CALLBACK althrd_callback_ = althrd_callback;
111 #endif
114 typedef struct thread_cntr {
115 althrd_start_t func;
116 void *arg;
117 } thread_cntr;
119 static DWORD WINAPI althrd_starter(void *arg)
121 thread_cntr cntr;
122 memcpy(&cntr, arg, sizeof(cntr));
123 free(arg);
125 return (DWORD)((*cntr.func)(cntr.arg));
129 int althrd_create(althrd_t *thr, althrd_start_t func, void *arg)
131 thread_cntr *cntr;
132 DWORD thrid;
133 HANDLE hdl;
135 cntr = malloc(sizeof(*cntr));
136 if(!cntr) return althrd_nomem;
138 cntr->func = func;
139 cntr->arg = arg;
141 hdl = CreateThread(NULL, THREAD_STACK_SIZE, althrd_starter, cntr, 0, &thrid);
142 if(!hdl)
144 free(cntr);
145 return althrd_error;
147 InsertUIntMapEntry(&ThrdIdHandle, thrid, hdl);
149 *thr = thrid;
150 return althrd_success;
153 int althrd_detach(althrd_t thr)
155 HANDLE hdl = RemoveUIntMapKey(&ThrdIdHandle, thr);
156 if(!hdl) return althrd_error;
158 CloseHandle(hdl);
159 return althrd_success;
162 int althrd_join(althrd_t thr, int *res)
164 DWORD code;
166 HANDLE hdl = RemoveUIntMapKey(&ThrdIdHandle, thr);
167 if(!hdl) return althrd_error;
169 WaitForSingleObject(hdl, INFINITE);
170 GetExitCodeThread(hdl, &code);
171 CloseHandle(hdl);
173 *res = (int)code;
174 return althrd_success;
177 int althrd_sleep(const struct timespec *ts, struct timespec* UNUSED(rem))
179 DWORD msec;
181 if(ts->tv_sec < 0 || ts->tv_sec >= (0x7fffffff / 1000) ||
182 ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
183 return -2;
185 msec = (DWORD)(ts->tv_sec * 1000);
186 msec += (DWORD)((ts->tv_nsec+999999) / 1000000);
187 Sleep(msec);
189 return 0;
193 int almtx_init(almtx_t *mtx, int type)
195 if(!mtx) return althrd_error;
196 type &= ~(almtx_recursive|almtx_timed);
197 if(type != almtx_plain)
198 return althrd_error;
200 InitializeCriticalSection(mtx);
201 return althrd_success;
204 void almtx_destroy(almtx_t *mtx)
206 DeleteCriticalSection(mtx);
209 int almtx_timedlock(almtx_t *mtx, const struct timespec *ts)
211 int ret;
213 if(!mtx || !ts)
214 return althrd_error;
216 while((ret=almtx_trylock(mtx)) == althrd_busy)
218 struct timespec now;
220 if(ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000 ||
221 altimespec_get(&now, AL_TIME_UTC) != AL_TIME_UTC)
222 return althrd_error;
223 if(now.tv_sec > ts->tv_sec || (now.tv_sec == ts->tv_sec && now.tv_nsec >= ts->tv_nsec))
224 return althrd_timedout;
226 althrd_yield();
229 return ret;
233 /* An associative map of uint:void* pairs. The key is the TLS index (given by
234 * TlsAlloc), and the value is the altss_dtor_t callback. When a thread exits,
235 * we iterate over the TLS indices for their thread-local value and call the
236 * destructor function with it if they're both not NULL. To avoid using
237 * DllMain, a PIMAGE_TLS_CALLBACK function pointer is placed in a ".CRT$XLx"
238 * section (where x is a character A to Z) which will be called by the CRT.
240 static UIntMap TlsDestructors = UINTMAP_STATIC_INITIALIZE;
242 static void NTAPI altss_callback(void* UNUSED(handle), DWORD reason, void* UNUSED(reserved))
244 ALsizei i;
246 if(reason == DLL_PROCESS_DETACH)
248 ResetUIntMap(&TlsDestructors);
249 return;
251 if(reason != DLL_THREAD_DETACH)
252 return;
254 LockUIntMapRead(&TlsDestructors);
255 for(i = 0;i < TlsDestructors.size;i++)
257 void *ptr = altss_get(TlsDestructors.array[i].key);
258 altss_dtor_t callback = (altss_dtor_t)TlsDestructors.array[i].value;
259 if(ptr && callback)
260 callback(ptr);
262 UnlockUIntMapRead(&TlsDestructors);
264 #ifdef _MSC_VER
265 #pragma section(".CRT$XLB",read)
266 __declspec(allocate(".CRT$XLB")) PIMAGE_TLS_CALLBACK altss_callback_ = altss_callback;
267 #elif defined(__GNUC__)
268 PIMAGE_TLS_CALLBACK altss_callback_ __attribute__((section(".CRT$XLB"))) = altss_callback;
269 #else
270 #warning "No TLS callback support, thread-local contexts may leak references on poorly written applications."
271 PIMAGE_TLS_CALLBACK altss_callback_ = altss_callback;
272 #endif
274 int altss_create(altss_t *tss_id, altss_dtor_t callback)
276 DWORD key = TlsAlloc();
277 if(key == TLS_OUT_OF_INDEXES)
278 return althrd_error;
280 *tss_id = key;
281 if(callback != NULL)
282 InsertUIntMapEntry(&TlsDestructors, key, callback);
283 return althrd_success;
286 void altss_delete(altss_t tss_id)
288 RemoveUIntMapKey(&TlsDestructors, tss_id);
289 TlsFree(tss_id);
293 int altimespec_get(struct timespec *ts, int base)
295 if(base == AL_TIME_UTC)
297 union {
298 FILETIME ftime;
299 ULARGE_INTEGER ulint;
300 } systime;
301 GetSystemTimeAsFileTime(&systime.ftime);
302 /* FILETIME is in 100-nanosecond units, or 1/10th of a microsecond. */
303 ts->tv_sec = systime.ulint.QuadPart/10000000;
304 ts->tv_nsec = (systime.ulint.QuadPart%10000000) * 100;
305 return base;
308 return 0;
312 void alcall_once(alonce_flag *once, void (*callback)(void))
314 LONG ret;
315 while((ret=InterlockedExchange(once, 1)) == 1)
316 althrd_yield();
317 if(ret == 0)
318 (*callback)();
319 InterlockedExchange(once, 2);
322 #else
324 #include <sys/time.h>
325 #include <unistd.h>
326 #include <pthread.h>
327 #ifdef HAVE_PTHREAD_NP_H
328 #include <pthread_np.h>
329 #endif
332 extern inline int althrd_sleep(const struct timespec *ts, struct timespec *rem);
333 extern inline void alcall_once(alonce_flag *once, void (*callback)(void));
336 void althrd_setname(althrd_t thr, const char *name)
338 #if defined(HAVE_PTHREAD_SETNAME_NP)
339 #if defined(__GNUC__)
340 pthread_setname_np(thr, name);
341 #elif defined(__APPLE__)
342 if(althrd_equal(thr, althrd_current())
343 pthread_setname_np(name);
344 #endif
345 #elif defined(HAVE_PTHREAD_SET_NAME_NP)
346 pthread_set_name_np(thr, name);
347 #else
348 (void)thr;
349 (void)name;
350 #endif
354 typedef struct thread_cntr {
355 althrd_start_t func;
356 void *arg;
357 } thread_cntr;
359 static void *althrd_starter(void *arg)
361 thread_cntr cntr;
362 memcpy(&cntr, arg, sizeof(cntr));
363 free(arg);
365 return (void*)(intptr_t)((*cntr.func)(cntr.arg));
369 int althrd_create(althrd_t *thr, althrd_start_t func, void *arg)
371 thread_cntr *cntr;
372 pthread_attr_t attr;
374 cntr = malloc(sizeof(*cntr));
375 if(!cntr) return althrd_nomem;
377 if(pthread_attr_init(&attr) != 0)
379 free(cntr);
380 return althrd_error;
382 if(pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE) != 0)
384 pthread_attr_destroy(&attr);
385 free(cntr);
386 return althrd_error;
389 cntr->func = func;
390 cntr->arg = arg;
391 if(pthread_create(thr, &attr, althrd_starter, cntr) != 0)
393 pthread_attr_destroy(&attr);
394 free(cntr);
395 return althrd_error;
397 pthread_attr_destroy(&attr);
399 return althrd_success;
402 int althrd_detach(althrd_t thr)
404 if(pthread_detach(thr) != 0)
405 return althrd_error;
406 return althrd_success;
409 int althrd_join(althrd_t thr, int *res)
411 void *code;
413 if(!res) return althrd_error;
415 if(pthread_join(thr, &code) != 0)
416 return althrd_error;
417 *res = (int)(intptr_t)code;
418 return althrd_success;
422 int almtx_init(almtx_t *mtx, int type)
424 int ret;
426 if(!mtx) return althrd_error;
427 if((type&~(almtx_recursive|almtx_timed)) != 0)
428 return althrd_error;
430 type &= ~almtx_timed;
431 if(type == almtx_plain)
432 ret = pthread_mutex_init(mtx, NULL);
433 else
435 pthread_mutexattr_t attr;
437 ret = pthread_mutexattr_init(&attr);
438 if(ret) return althrd_error;
440 if(type == almtx_recursive)
442 ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
443 #ifdef HAVE_PTHREAD_MUTEXATTR_SETKIND_NP
444 if(ret != 0)
445 ret = pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_RECURSIVE);
446 #endif
448 else
449 ret = 1;
450 if(ret == 0)
451 ret = pthread_mutex_init(mtx, &attr);
452 pthread_mutexattr_destroy(&attr);
454 return ret ? althrd_error : althrd_success;
457 void almtx_destroy(almtx_t *mtx)
459 pthread_mutex_destroy(mtx);
462 int almtx_timedlock(almtx_t *mtx, const struct timespec *ts)
464 int ret;
466 #ifdef HAVE_PTHREAD_MUTEX_TIMEDLOCK
467 ret = pthread_mutex_timedlock(mtx, ts);
468 switch(ret)
470 case 0: return althrd_success;
471 case ETIMEDOUT: return althrd_timedout;
472 case EBUSY: return althrd_busy;
474 return althrd_error;
475 #else
476 if(!mtx || !ts)
477 return althrd_error;
479 while((ret=almtx_trylock(mtx)) == althrd_busy)
481 struct timespec now;
483 if(ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000 ||
484 altimespec_get(&now, AL_TIME_UTC) != AL_TIME_UTC)
485 return althrd_error;
486 if(now.tv_sec > ts->tv_sec || (now.tv_sec == ts->tv_sec && now.tv_nsec >= ts->tv_nsec))
487 return althrd_timedout;
489 althrd_yield();
492 return ret;
493 #endif
497 int altss_create(altss_t *tss_id, altss_dtor_t callback)
499 if(pthread_key_create(tss_id, callback) != 0)
500 return althrd_error;
501 return althrd_success;
504 void altss_delete(altss_t tss_id)
506 pthread_key_delete(tss_id);
510 int altimespec_get(struct timespec *ts, int base)
512 if(base == AL_TIME_UTC)
514 int ret;
515 #if _POSIX_TIMERS > 0
516 ret = clock_gettime(CLOCK_REALTIME, ts);
517 if(ret == 0) return base;
518 #else /* _POSIX_TIMERS > 0 */
519 struct timeval tv;
520 ret = gettimeofday(&tv, NULL);
521 if(ret == 0)
523 ts->tv_sec = tv.tv_sec;
524 ts->tv_nsec = tv.tv_usec * 1000;
525 return base;
527 #endif
530 return 0;
533 #endif
536 void al_nssleep(time_t sec, long nsec)
538 struct timespec ts, rem;
539 ts.tv_sec = sec;
540 ts.tv_nsec = nsec;
542 while(althrd_sleep(&ts, &rem) == -1)
543 ts = rem;