Remove unnecessary code for the now-unused write offset
[openal-soft.git] / common / threads.c
blob5a177a2c9e3ad9c5f10e5a53f75a13ccfe113025
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.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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 if(res != NULL)
174 *res = (int)code;
175 return althrd_success;
178 int althrd_sleep(const struct timespec *ts, struct timespec* UNUSED(rem))
180 DWORD msec;
182 if(ts->tv_sec < 0 || ts->tv_sec >= (0x7fffffff / 1000) ||
183 ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
184 return -2;
186 msec = (DWORD)(ts->tv_sec * 1000);
187 msec += (DWORD)((ts->tv_nsec+999999) / 1000000);
188 Sleep(msec);
190 return 0;
194 int almtx_init(almtx_t *mtx, int type)
196 if(!mtx) return althrd_error;
197 type &= ~(almtx_recursive|almtx_timed);
198 if(type != almtx_plain)
199 return althrd_error;
201 InitializeCriticalSection(mtx);
202 return althrd_success;
205 void almtx_destroy(almtx_t *mtx)
207 DeleteCriticalSection(mtx);
210 int almtx_timedlock(almtx_t *mtx, const struct timespec *ts)
212 int ret;
214 if(!mtx || !ts)
215 return althrd_error;
217 while((ret=almtx_trylock(mtx)) == althrd_busy)
219 struct timespec now;
221 if(ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000 ||
222 altimespec_get(&now, AL_TIME_UTC) != AL_TIME_UTC)
223 return althrd_error;
224 if(now.tv_sec > ts->tv_sec || (now.tv_sec == ts->tv_sec && now.tv_nsec >= ts->tv_nsec))
225 return althrd_timedout;
227 althrd_yield();
230 return ret;
233 #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0600
234 int alcnd_init(alcnd_t *cond)
236 InitializeConditionVariable(cond);
237 return althrd_success;
240 int alcnd_signal(alcnd_t *cond)
242 WakeConditionVariable(cond);
243 return althrd_success;
246 int alcnd_broadcast(alcnd_t *cond)
248 WakeAllConditionVariable(cond);
249 return althrd_success;
252 int alcnd_wait(alcnd_t *cond, almtx_t *mtx)
254 if(SleepConditionVariableCS(cond, mtx, INFINITE) != 0)
255 return althrd_success;
256 return althrd_error;
259 int alcnd_timedwait(alcnd_t *cond, almtx_t *mtx, const struct timespec *time_point)
261 struct timespec curtime;
262 DWORD sleeptime;
264 if(altimespec_get(&curtime, AL_TIME_UTC) != AL_TIME_UTC)
265 return althrd_error;
267 if(curtime.tv_sec > time_point->tv_sec || (curtime.tv_sec == time_point->tv_sec &&
268 curtime.tv_nsec >= time_point->tv_nsec))
270 if(SleepConditionVariableCS(cond, mtx, 0) != 0)
271 return althrd_success;
273 else
275 sleeptime = (time_point->tv_nsec - curtime.tv_nsec + 999999)/1000000;
276 sleeptime += (time_point->tv_sec - curtime.tv_sec)*1000;
277 if(SleepConditionVariableCS(cond, mtx, sleeptime) != 0)
278 return althrd_success;
280 return (GetLastError()==ERROR_TIMEOUT) ? althrd_timedout : althrd_error;
283 void alcnd_destroy(alcnd_t* UNUSED(cond))
285 /* Nothing to delete? */
288 #else
290 /* WARNING: This is a rather poor implementation of condition variables, with
291 * known problems. However, it's simple, efficient, and good enough for now to
292 * not require Vista. Based on "Strategies for Implementing POSIX Condition
293 * Variables" by Douglas C. Schmidt and Irfan Pyarali:
294 * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
296 /* A better solution may be using Wine's implementation. It requires internals
297 * (NtCreateKeyedEvent, NtReleaseKeyedEvent, and NtWaitForKeyedEvent) from
298 * ntdll, and implemention of exchange and compare-exchange for RefCounts.
301 typedef struct {
302 RefCount wait_count;
304 HANDLE events[2];
305 } _int_alcnd_t;
306 enum {
307 SIGNAL = 0,
308 BROADCAST = 1
311 int alcnd_init(alcnd_t *cond)
313 _int_alcnd_t *icond = calloc(1, sizeof(*icond));
314 if(!icond) return althrd_nomem;
316 InitRef(&icond->wait_count, 0);
318 icond->events[SIGNAL] = CreateEventW(NULL, FALSE, FALSE, NULL);
319 icond->events[BROADCAST] = CreateEventW(NULL, TRUE, FALSE, NULL);
320 if(!icond->events[SIGNAL] || !icond->events[BROADCAST])
322 if(icond->events[SIGNAL])
323 CloseHandle(icond->events[SIGNAL]);
324 if(icond->events[BROADCAST])
325 CloseHandle(icond->events[BROADCAST]);
326 free(icond);
327 return althrd_error;
330 cond->Ptr = icond;
331 return althrd_success;
334 int alcnd_signal(alcnd_t *cond)
336 _int_alcnd_t *icond = cond->Ptr;
337 if(ReadRef(&icond->wait_count) > 0)
338 SetEvent(icond->events[SIGNAL]);
339 return althrd_success;
342 int alcnd_broadcast(alcnd_t *cond)
344 _int_alcnd_t *icond = cond->Ptr;
345 if(ReadRef(&icond->wait_count) > 0)
346 SetEvent(icond->events[BROADCAST]);
347 return althrd_success;
350 int alcnd_wait(alcnd_t *cond, almtx_t *mtx)
352 _int_alcnd_t *icond = cond->Ptr;
353 int res;
355 IncrementRef(&icond->wait_count);
356 LeaveCriticalSection(mtx);
358 res = WaitForMultipleObjects(2, icond->events, FALSE, INFINITE);
360 if(DecrementRef(&icond->wait_count) == 0 && res == WAIT_OBJECT_0+BROADCAST)
361 ResetEvent(icond->events[BROADCAST]);
362 EnterCriticalSection(mtx);
364 return althrd_success;
367 int alcnd_timedwait(alcnd_t *cond, almtx_t *mtx, const struct timespec *time_point)
369 _int_alcnd_t *icond = cond->Ptr;
370 struct timespec curtime;
371 DWORD sleeptime;
372 int res;
374 if(altimespec_get(&curtime, AL_TIME_UTC) != AL_TIME_UTC)
375 return althrd_error;
377 if(curtime.tv_sec > time_point->tv_sec || (curtime.tv_sec == time_point->tv_sec &&
378 curtime.tv_nsec >= time_point->tv_nsec))
379 sleeptime = 0;
380 else
382 sleeptime = (time_point->tv_nsec - curtime.tv_nsec + 999999)/1000000;
383 sleeptime += (time_point->tv_sec - curtime.tv_sec)*1000;
386 IncrementRef(&icond->wait_count);
387 LeaveCriticalSection(mtx);
389 res = WaitForMultipleObjects(2, icond->events, FALSE, sleeptime);
391 if(DecrementRef(&icond->wait_count) == 0 && res == WAIT_OBJECT_0+BROADCAST)
392 ResetEvent(icond->events[BROADCAST]);
393 EnterCriticalSection(mtx);
395 return (res == WAIT_TIMEOUT) ? althrd_timedout : althrd_success;
398 void alcnd_destroy(alcnd_t *cond)
400 _int_alcnd_t *icond = cond->Ptr;
401 CloseHandle(icond->events[SIGNAL]);
402 CloseHandle(icond->events[BROADCAST]);
403 free(icond);
405 #endif /* defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0600 */
408 /* An associative map of uint:void* pairs. The key is the TLS index (given by
409 * TlsAlloc), and the value is the altss_dtor_t callback. When a thread exits,
410 * we iterate over the TLS indices for their thread-local value and call the
411 * destructor function with it if they're both not NULL. To avoid using
412 * DllMain, a PIMAGE_TLS_CALLBACK function pointer is placed in a ".CRT$XLx"
413 * section (where x is a character A to Z) which will be called by the CRT.
415 static UIntMap TlsDestructors = UINTMAP_STATIC_INITIALIZE;
417 static void NTAPI altss_callback(void* UNUSED(handle), DWORD reason, void* UNUSED(reserved))
419 ALsizei i;
421 if(reason == DLL_PROCESS_DETACH)
423 ResetUIntMap(&TlsDestructors);
424 return;
426 if(reason != DLL_THREAD_DETACH)
427 return;
429 LockUIntMapRead(&TlsDestructors);
430 for(i = 0;i < TlsDestructors.size;i++)
432 void *ptr = altss_get(TlsDestructors.array[i].key);
433 altss_dtor_t callback = (altss_dtor_t)TlsDestructors.array[i].value;
434 if(ptr && callback)
435 callback(ptr);
437 UnlockUIntMapRead(&TlsDestructors);
439 #ifdef _MSC_VER
440 #pragma section(".CRT$XLB",read)
441 __declspec(allocate(".CRT$XLB")) PIMAGE_TLS_CALLBACK altss_callback_ = altss_callback;
442 #elif defined(__GNUC__)
443 PIMAGE_TLS_CALLBACK altss_callback_ __attribute__((section(".CRT$XLB"))) = altss_callback;
444 #else
445 #warning "No TLS callback support, thread-local contexts may leak references on poorly written applications."
446 PIMAGE_TLS_CALLBACK altss_callback_ = altss_callback;
447 #endif
449 int altss_create(altss_t *tss_id, altss_dtor_t callback)
451 DWORD key = TlsAlloc();
452 if(key == TLS_OUT_OF_INDEXES)
453 return althrd_error;
455 *tss_id = key;
456 if(callback != NULL)
457 InsertUIntMapEntry(&TlsDestructors, key, callback);
458 return althrd_success;
461 void altss_delete(altss_t tss_id)
463 RemoveUIntMapKey(&TlsDestructors, tss_id);
464 TlsFree(tss_id);
468 int altimespec_get(struct timespec *ts, int base)
470 static_assert(sizeof(FILETIME) == sizeof(ULARGE_INTEGER),
471 "Size of FILETIME does not match ULARGE_INTEGER");
472 if(base == AL_TIME_UTC)
474 union {
475 FILETIME ftime;
476 ULARGE_INTEGER ulint;
477 } systime;
478 GetSystemTimeAsFileTime(&systime.ftime);
479 /* FILETIME is in 100-nanosecond units, or 1/10th of a microsecond. */
480 ts->tv_sec = systime.ulint.QuadPart/10000000;
481 ts->tv_nsec = (systime.ulint.QuadPart%10000000) * 100;
482 return base;
485 return 0;
489 void alcall_once(alonce_flag *once, void (*callback)(void))
491 LONG ret;
492 while((ret=InterlockedExchange(once, 1)) == 1)
493 althrd_yield();
494 if(ret == 0)
495 (*callback)();
496 InterlockedExchange(once, 2);
499 #else
501 #include <sys/time.h>
502 #include <unistd.h>
503 #include <pthread.h>
504 #ifdef HAVE_PTHREAD_NP_H
505 #include <pthread_np.h>
506 #endif
509 extern inline int althrd_sleep(const struct timespec *ts, struct timespec *rem);
510 extern inline void alcall_once(alonce_flag *once, void (*callback)(void));
513 void althrd_setname(althrd_t thr, const char *name)
515 #if defined(HAVE_PTHREAD_SETNAME_NP)
516 #if defined(PTHREAD_SETNAME_NP_ONE_PARAM)
517 if(althrd_equal(thr, althrd_current()))
518 pthread_setname_np(name);
519 #else
520 pthread_setname_np(thr, name);
521 #endif
522 #elif defined(HAVE_PTHREAD_SET_NAME_NP)
523 pthread_set_name_np(thr, name);
524 #else
525 (void)thr;
526 (void)name;
527 #endif
531 typedef struct thread_cntr {
532 althrd_start_t func;
533 void *arg;
534 } thread_cntr;
536 static void *althrd_starter(void *arg)
538 thread_cntr cntr;
539 memcpy(&cntr, arg, sizeof(cntr));
540 free(arg);
542 return (void*)(intptr_t)((*cntr.func)(cntr.arg));
546 int althrd_create(althrd_t *thr, althrd_start_t func, void *arg)
548 thread_cntr *cntr;
549 pthread_attr_t attr;
551 cntr = malloc(sizeof(*cntr));
552 if(!cntr) return althrd_nomem;
554 if(pthread_attr_init(&attr) != 0)
556 free(cntr);
557 return althrd_error;
559 if(pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE) != 0)
561 pthread_attr_destroy(&attr);
562 free(cntr);
563 return althrd_error;
566 cntr->func = func;
567 cntr->arg = arg;
568 if(pthread_create(thr, &attr, althrd_starter, cntr) != 0)
570 pthread_attr_destroy(&attr);
571 free(cntr);
572 return althrd_error;
574 pthread_attr_destroy(&attr);
576 return althrd_success;
579 int althrd_detach(althrd_t thr)
581 if(pthread_detach(thr) != 0)
582 return althrd_error;
583 return althrd_success;
586 int althrd_join(althrd_t thr, int *res)
588 void *code;
590 if(pthread_join(thr, &code) != 0)
591 return althrd_error;
592 if(res != NULL)
593 *res = (int)(intptr_t)code;
594 return althrd_success;
598 int almtx_init(almtx_t *mtx, int type)
600 int ret;
602 if(!mtx) return althrd_error;
603 if((type&~(almtx_recursive|almtx_timed)) != 0)
604 return althrd_error;
606 type &= ~almtx_timed;
607 if(type == almtx_plain)
608 ret = pthread_mutex_init(mtx, NULL);
609 else
611 pthread_mutexattr_t attr;
613 ret = pthread_mutexattr_init(&attr);
614 if(ret) return althrd_error;
616 if(type == almtx_recursive)
618 ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
619 #ifdef HAVE_PTHREAD_MUTEXATTR_SETKIND_NP
620 if(ret != 0)
621 ret = pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_RECURSIVE);
622 #endif
624 else
625 ret = 1;
626 if(ret == 0)
627 ret = pthread_mutex_init(mtx, &attr);
628 pthread_mutexattr_destroy(&attr);
630 return ret ? althrd_error : althrd_success;
633 void almtx_destroy(almtx_t *mtx)
635 pthread_mutex_destroy(mtx);
638 int almtx_timedlock(almtx_t *mtx, const struct timespec *ts)
640 int ret;
642 #ifdef HAVE_PTHREAD_MUTEX_TIMEDLOCK
643 ret = pthread_mutex_timedlock(mtx, ts);
644 switch(ret)
646 case 0: return althrd_success;
647 case ETIMEDOUT: return althrd_timedout;
648 case EBUSY: return althrd_busy;
650 return althrd_error;
651 #else
652 if(!mtx || !ts)
653 return althrd_error;
655 while((ret=almtx_trylock(mtx)) == althrd_busy)
657 struct timespec now;
659 if(ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000 ||
660 altimespec_get(&now, AL_TIME_UTC) != AL_TIME_UTC)
661 return althrd_error;
662 if(now.tv_sec > ts->tv_sec || (now.tv_sec == ts->tv_sec && now.tv_nsec >= ts->tv_nsec))
663 return althrd_timedout;
665 althrd_yield();
668 return ret;
669 #endif
672 int alcnd_init(alcnd_t *cond)
674 if(pthread_cond_init(cond, NULL) == 0)
675 return althrd_success;
676 return althrd_error;
679 int alcnd_signal(alcnd_t *cond)
681 if(pthread_cond_signal(cond) == 0)
682 return althrd_success;
683 return althrd_error;
686 int alcnd_broadcast(alcnd_t *cond)
688 if(pthread_cond_broadcast(cond) == 0)
689 return althrd_success;
690 return althrd_error;
693 int alcnd_wait(alcnd_t *cond, almtx_t *mtx)
695 if(pthread_cond_wait(cond, mtx) == 0)
696 return althrd_success;
697 return althrd_error;
700 int alcnd_timedwait(alcnd_t *cond, almtx_t *mtx, const struct timespec *time_point)
702 if(pthread_cond_timedwait(cond, mtx, time_point) == 0)
703 return althrd_success;
704 return althrd_error;
707 void alcnd_destroy(alcnd_t *cond)
709 pthread_cond_destroy(cond);
713 int altss_create(altss_t *tss_id, altss_dtor_t callback)
715 if(pthread_key_create(tss_id, callback) != 0)
716 return althrd_error;
717 return althrd_success;
720 void altss_delete(altss_t tss_id)
722 pthread_key_delete(tss_id);
726 int altimespec_get(struct timespec *ts, int base)
728 if(base == AL_TIME_UTC)
730 int ret;
731 #if _POSIX_TIMERS > 0
732 ret = clock_gettime(CLOCK_REALTIME, ts);
733 if(ret == 0) return base;
734 #else /* _POSIX_TIMERS > 0 */
735 struct timeval tv;
736 ret = gettimeofday(&tv, NULL);
737 if(ret == 0)
739 ts->tv_sec = tv.tv_sec;
740 ts->tv_nsec = tv.tv_usec * 1000;
741 return base;
743 #endif
746 return 0;
749 #endif
752 void al_nssleep(unsigned long nsec)
754 struct timespec ts, rem;
755 ts.tv_sec = nsec / 1000000000ul;
756 ts.tv_nsec = nsec % 1000000000ul;
758 while(althrd_sleep(&ts, &rem) == -1)
759 ts = rem;