threads.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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.
  8. *
  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.
  13. *
  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
  19. */
  20. #include "config.h"
  21. #include "threads.h"
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <errno.h>
  25. #include "uintmap.h"
  26. extern inline althrd_t althrd_current(void);
  27. extern inline int althrd_equal(althrd_t thr0, althrd_t thr1);
  28. extern inline void althrd_exit(int res);
  29. extern inline void althrd_yield(void);
  30. extern inline int almtx_lock(almtx_t *mtx);
  31. extern inline int almtx_unlock(almtx_t *mtx);
  32. extern inline int almtx_trylock(almtx_t *mtx);
  33. extern inline void *altss_get(altss_t tss_id);
  34. extern inline int altss_set(altss_t tss_id, void *val);
  35. #ifndef UNUSED
  36. #if defined(__cplusplus)
  37. #define UNUSED(x)
  38. #elif defined(__GNUC__)
  39. #define UNUSED(x) UNUSED_##x __attribute__((unused))
  40. #elif defined(__LCLINT__)
  41. #define UNUSED(x) /*@unused@*/ x
  42. #else
  43. #define UNUSED(x) x
  44. #endif
  45. #endif
  46. #define THREAD_STACK_SIZE (2*1024*1024) /* 2MB */
  47. #ifdef _WIN32
  48. #define WIN32_LEAN_AND_MEAN
  49. #include <windows.h>
  50. #include <mmsystem.h>
  51. /* An associative map of uint:void* pairs. The key is the unique Thread ID and
  52. * the value is the thread HANDLE. The thread ID is passed around as the
  53. * althrd_t since there is only one ID per thread, whereas a thread may be
  54. * referenced by multiple different HANDLEs. This map allows retrieving the
  55. * original handle which is needed to join the thread and get its return value.
  56. */
  57. static UIntMap ThrdIdHandle = UINTMAP_STATIC_INITIALIZE;
  58. /* An associative map of uint:void* pairs. The key is the TLS index (given by
  59. * TlsAlloc), and the value is the altss_dtor_t callback. When a thread exits,
  60. * we iterate over the TLS indices for their thread-local value and call the
  61. * destructor function with it if they're both not NULL.
  62. */
  63. static UIntMap TlsDestructors = UINTMAP_STATIC_INITIALIZE;
  64. void althrd_setname(althrd_t thr, const char *name)
  65. {
  66. #if defined(_MSC_VER)
  67. #define MS_VC_EXCEPTION 0x406D1388
  68. #pragma pack(push,8)
  69. struct {
  70. DWORD dwType; // Must be 0x1000.
  71. LPCSTR szName; // Pointer to name (in user addr space).
  72. DWORD dwThreadID; // Thread ID (-1=caller thread).
  73. DWORD dwFlags; // Reserved for future use, must be zero.
  74. } info;
  75. #pragma pack(pop)
  76. info.dwType = 0x1000;
  77. info.szName = name;
  78. info.dwThreadID = thr;
  79. info.dwFlags = 0;
  80. __try {
  81. RaiseException(MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info);
  82. }
  83. __except(EXCEPTION_CONTINUE_EXECUTION) {
  84. }
  85. #undef MS_VC_EXCEPTION
  86. #else
  87. (void)thr;
  88. (void)name;
  89. #endif
  90. }
  91. typedef struct thread_cntr {
  92. althrd_start_t func;
  93. void *arg;
  94. } thread_cntr;
  95. static DWORD WINAPI althrd_starter(void *arg)
  96. {
  97. thread_cntr cntr;
  98. memcpy(&cntr, arg, sizeof(cntr));
  99. free(arg);
  100. return (DWORD)((*cntr.func)(cntr.arg));
  101. }
  102. int althrd_create(althrd_t *thr, althrd_start_t func, void *arg)
  103. {
  104. thread_cntr *cntr;
  105. DWORD thrid;
  106. HANDLE hdl;
  107. cntr = malloc(sizeof(*cntr));
  108. if(!cntr) return althrd_nomem;
  109. cntr->func = func;
  110. cntr->arg = arg;
  111. hdl = CreateThread(NULL, THREAD_STACK_SIZE, althrd_starter, cntr, 0, &thrid);
  112. if(!hdl)
  113. {
  114. free(cntr);
  115. return althrd_error;
  116. }
  117. InsertUIntMapEntry(&ThrdIdHandle, thrid, hdl);
  118. *thr = thrid;
  119. return althrd_success;
  120. }
  121. int althrd_detach(althrd_t thr)
  122. {
  123. HANDLE hdl = RemoveUIntMapKey(&ThrdIdHandle, thr);
  124. if(!hdl) return althrd_error;
  125. CloseHandle(hdl);
  126. return althrd_success;
  127. }
  128. int althrd_join(althrd_t thr, int *res)
  129. {
  130. DWORD code;
  131. HANDLE hdl = RemoveUIntMapKey(&ThrdIdHandle, thr);
  132. if(!hdl) return althrd_error;
  133. WaitForSingleObject(hdl, INFINITE);
  134. GetExitCodeThread(hdl, &code);
  135. CloseHandle(hdl);
  136. if(res != NULL)
  137. *res = (int)code;
  138. return althrd_success;
  139. }
  140. int althrd_sleep(const struct timespec *ts, struct timespec* UNUSED(rem))
  141. {
  142. DWORD msec;
  143. if(ts->tv_sec < 0 || ts->tv_sec >= (0x7fffffff / 1000) ||
  144. ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
  145. return -2;
  146. msec = (DWORD)(ts->tv_sec * 1000);
  147. msec += (DWORD)((ts->tv_nsec+999999) / 1000000);
  148. Sleep(msec);
  149. return 0;
  150. }
  151. int almtx_init(almtx_t *mtx, int type)
  152. {
  153. if(!mtx) return althrd_error;
  154. type &= ~almtx_recursive;
  155. if(type != almtx_plain)
  156. return althrd_error;
  157. InitializeCriticalSection(mtx);
  158. return althrd_success;
  159. }
  160. void almtx_destroy(almtx_t *mtx)
  161. {
  162. DeleteCriticalSection(mtx);
  163. }
  164. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0600
  165. int alcnd_init(alcnd_t *cond)
  166. {
  167. InitializeConditionVariable(cond);
  168. return althrd_success;
  169. }
  170. int alcnd_signal(alcnd_t *cond)
  171. {
  172. WakeConditionVariable(cond);
  173. return althrd_success;
  174. }
  175. int alcnd_broadcast(alcnd_t *cond)
  176. {
  177. WakeAllConditionVariable(cond);
  178. return althrd_success;
  179. }
  180. int alcnd_wait(alcnd_t *cond, almtx_t *mtx)
  181. {
  182. if(SleepConditionVariableCS(cond, mtx, INFINITE) != 0)
  183. return althrd_success;
  184. return althrd_error;
  185. }
  186. void alcnd_destroy(alcnd_t* UNUSED(cond))
  187. {
  188. /* Nothing to delete? */
  189. }
  190. #else
  191. /* WARNING: This is a rather poor implementation of condition variables, with
  192. * known problems. However, it's simple, efficient, and good enough for now to
  193. * not require Vista. Based on "Strategies for Implementing POSIX Condition
  194. * Variables" by Douglas C. Schmidt and Irfan Pyarali:
  195. * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
  196. */
  197. /* A better solution may be using Wine's implementation. It requires internals
  198. * (NtCreateKeyedEvent, NtReleaseKeyedEvent, and NtWaitForKeyedEvent) from
  199. * ntdll, and implemention of exchange and compare-exchange for RefCounts.
  200. */
  201. typedef struct {
  202. RefCount wait_count;
  203. HANDLE events[2];
  204. } _int_alcnd_t;
  205. enum {
  206. SIGNAL = 0,
  207. BROADCAST = 1
  208. };
  209. int alcnd_init(alcnd_t *cond)
  210. {
  211. _int_alcnd_t *icond = calloc(1, sizeof(*icond));
  212. if(!icond) return althrd_nomem;
  213. InitRef(&icond->wait_count, 0);
  214. icond->events[SIGNAL] = CreateEventW(NULL, FALSE, FALSE, NULL);
  215. icond->events[BROADCAST] = CreateEventW(NULL, TRUE, FALSE, NULL);
  216. if(!icond->events[SIGNAL] || !icond->events[BROADCAST])
  217. {
  218. if(icond->events[SIGNAL])
  219. CloseHandle(icond->events[SIGNAL]);
  220. if(icond->events[BROADCAST])
  221. CloseHandle(icond->events[BROADCAST]);
  222. free(icond);
  223. return althrd_error;
  224. }
  225. cond->Ptr = icond;
  226. return althrd_success;
  227. }
  228. int alcnd_signal(alcnd_t *cond)
  229. {
  230. _int_alcnd_t *icond = cond->Ptr;
  231. if(ReadRef(&icond->wait_count) > 0)
  232. SetEvent(icond->events[SIGNAL]);
  233. return althrd_success;
  234. }
  235. int alcnd_broadcast(alcnd_t *cond)
  236. {
  237. _int_alcnd_t *icond = cond->Ptr;
  238. if(ReadRef(&icond->wait_count) > 0)
  239. SetEvent(icond->events[BROADCAST]);
  240. return althrd_success;
  241. }
  242. int alcnd_wait(alcnd_t *cond, almtx_t *mtx)
  243. {
  244. _int_alcnd_t *icond = cond->Ptr;
  245. int res;
  246. IncrementRef(&icond->wait_count);
  247. LeaveCriticalSection(mtx);
  248. res = WaitForMultipleObjects(2, icond->events, FALSE, INFINITE);
  249. if(DecrementRef(&icond->wait_count) == 0 && res == WAIT_OBJECT_0+BROADCAST)
  250. ResetEvent(icond->events[BROADCAST]);
  251. EnterCriticalSection(mtx);
  252. return althrd_success;
  253. }
  254. void alcnd_destroy(alcnd_t *cond)
  255. {
  256. _int_alcnd_t *icond = cond->Ptr;
  257. CloseHandle(icond->events[SIGNAL]);
  258. CloseHandle(icond->events[BROADCAST]);
  259. free(icond);
  260. }
  261. #endif /* defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0600 */
  262. int alsem_init(alsem_t *sem, unsigned int initial)
  263. {
  264. *sem = CreateSemaphore(NULL, initial, INT_MAX, NULL);
  265. if(*sem != NULL) return althrd_success;
  266. return althrd_error;
  267. }
  268. void alsem_destroy(alsem_t *sem)
  269. {
  270. CloseHandle(*sem);
  271. }
  272. int alsem_post(alsem_t *sem)
  273. {
  274. DWORD ret = ReleaseSemaphore(*sem, 1, NULL);
  275. if(ret) return althrd_success;
  276. return althrd_error;
  277. }
  278. int alsem_wait(alsem_t *sem)
  279. {
  280. DWORD ret = WaitForSingleObject(*sem, INFINITE);
  281. if(ret == WAIT_OBJECT_0) return althrd_success;
  282. return althrd_error;
  283. }
  284. int alsem_trywait(alsem_t *sem)
  285. {
  286. DWORD ret = WaitForSingleObject(*sem, 0);
  287. if(ret == WAIT_OBJECT_0) return althrd_success;
  288. if(ret == WAIT_TIMEOUT) return althrd_busy;
  289. return althrd_error;
  290. }
  291. int altss_create(altss_t *tss_id, altss_dtor_t callback)
  292. {
  293. DWORD key = TlsAlloc();
  294. if(key == TLS_OUT_OF_INDEXES)
  295. return althrd_error;
  296. *tss_id = key;
  297. if(callback != NULL)
  298. InsertUIntMapEntry(&TlsDestructors, key, callback);
  299. return althrd_success;
  300. }
  301. void altss_delete(altss_t tss_id)
  302. {
  303. RemoveUIntMapKey(&TlsDestructors, tss_id);
  304. TlsFree(tss_id);
  305. }
  306. int altimespec_get(struct timespec *ts, int base)
  307. {
  308. static_assert(sizeof(FILETIME) == sizeof(ULARGE_INTEGER),
  309. "Size of FILETIME does not match ULARGE_INTEGER");
  310. if(base == AL_TIME_UTC)
  311. {
  312. union {
  313. FILETIME ftime;
  314. ULARGE_INTEGER ulint;
  315. } systime;
  316. GetSystemTimeAsFileTime(&systime.ftime);
  317. /* FILETIME is in 100-nanosecond units, or 1/10th of a microsecond. */
  318. ts->tv_sec = systime.ulint.QuadPart/10000000;
  319. ts->tv_nsec = (systime.ulint.QuadPart%10000000) * 100;
  320. return base;
  321. }
  322. return 0;
  323. }
  324. void alcall_once(alonce_flag *once, void (*callback)(void))
  325. {
  326. LONG ret;
  327. while((ret=InterlockedExchange(once, 1)) == 1)
  328. althrd_yield();
  329. if(ret == 0)
  330. (*callback)();
  331. InterlockedExchange(once, 2);
  332. }
  333. void althrd_deinit(void)
  334. {
  335. ResetUIntMap(&ThrdIdHandle);
  336. ResetUIntMap(&TlsDestructors);
  337. }
  338. void althrd_thread_detach(void)
  339. {
  340. ALsizei i;
  341. LockUIntMapRead(&TlsDestructors);
  342. for(i = 0;i < TlsDestructors.size;i++)
  343. {
  344. void *ptr = altss_get(TlsDestructors.keys[i]);
  345. altss_dtor_t callback = (altss_dtor_t)TlsDestructors.values[i];
  346. if(ptr)
  347. {
  348. if(callback) callback(ptr);
  349. altss_set(TlsDestructors.keys[i], NULL);
  350. }
  351. }
  352. UnlockUIntMapRead(&TlsDestructors);
  353. }
  354. #else
  355. #include <sys/time.h>
  356. #include <unistd.h>
  357. #include <pthread.h>
  358. #ifdef HAVE_PTHREAD_NP_H
  359. #include <pthread_np.h>
  360. #endif
  361. extern inline int althrd_sleep(const struct timespec *ts, struct timespec *rem);
  362. extern inline void alcall_once(alonce_flag *once, void (*callback)(void));
  363. extern inline void althrd_deinit(void);
  364. extern inline void althrd_thread_detach(void);
  365. void althrd_setname(althrd_t thr, const char *name)
  366. {
  367. #if defined(HAVE_PTHREAD_SETNAME_NP)
  368. #if defined(PTHREAD_SETNAME_NP_ONE_PARAM)
  369. if(althrd_equal(thr, althrd_current()))
  370. pthread_setname_np(name);
  371. #elif defined(PTHREAD_SETNAME_NP_THREE_PARAMS)
  372. pthread_setname_np(thr, "%s", (void*)name);
  373. #else
  374. pthread_setname_np(thr, name);
  375. #endif
  376. #elif defined(HAVE_PTHREAD_SET_NAME_NP)
  377. pthread_set_name_np(thr, name);
  378. #else
  379. (void)thr;
  380. (void)name;
  381. #endif
  382. }
  383. typedef struct thread_cntr {
  384. althrd_start_t func;
  385. void *arg;
  386. } thread_cntr;
  387. static void *althrd_starter(void *arg)
  388. {
  389. thread_cntr cntr;
  390. memcpy(&cntr, arg, sizeof(cntr));
  391. free(arg);
  392. return (void*)(intptr_t)((*cntr.func)(cntr.arg));
  393. }
  394. int althrd_create(althrd_t *thr, althrd_start_t func, void *arg)
  395. {
  396. thread_cntr *cntr;
  397. pthread_attr_t attr;
  398. size_t stackmult = 1;
  399. int err;
  400. cntr = malloc(sizeof(*cntr));
  401. if(!cntr) return althrd_nomem;
  402. if(pthread_attr_init(&attr) != 0)
  403. {
  404. free(cntr);
  405. return althrd_error;
  406. }
  407. retry_stacksize:
  408. if(pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE*stackmult) != 0)
  409. {
  410. pthread_attr_destroy(&attr);
  411. free(cntr);
  412. return althrd_error;
  413. }
  414. cntr->func = func;
  415. cntr->arg = arg;
  416. if((err=pthread_create(thr, &attr, althrd_starter, cntr)) == 0)
  417. {
  418. pthread_attr_destroy(&attr);
  419. return althrd_success;
  420. }
  421. if(err == EINVAL)
  422. {
  423. /* If an invalid stack size, try increasing it (limit x4, 8MB). */
  424. if(stackmult < 4)
  425. {
  426. stackmult *= 2;
  427. goto retry_stacksize;
  428. }
  429. /* If still nothing, try defaults and hope they're good enough. */
  430. if(pthread_create(thr, NULL, althrd_starter, cntr) == 0)
  431. {
  432. pthread_attr_destroy(&attr);
  433. return althrd_success;
  434. }
  435. }
  436. pthread_attr_destroy(&attr);
  437. free(cntr);
  438. return althrd_error;
  439. }
  440. int althrd_detach(althrd_t thr)
  441. {
  442. if(pthread_detach(thr) != 0)
  443. return althrd_error;
  444. return althrd_success;
  445. }
  446. int althrd_join(althrd_t thr, int *res)
  447. {
  448. void *code;
  449. if(pthread_join(thr, &code) != 0)
  450. return althrd_error;
  451. if(res != NULL)
  452. *res = (int)(intptr_t)code;
  453. return althrd_success;
  454. }
  455. int almtx_init(almtx_t *mtx, int type)
  456. {
  457. int ret;
  458. if(!mtx) return althrd_error;
  459. if((type&~almtx_recursive) != 0)
  460. return althrd_error;
  461. if(type == almtx_plain)
  462. ret = pthread_mutex_init(mtx, NULL);
  463. else
  464. {
  465. pthread_mutexattr_t attr;
  466. ret = pthread_mutexattr_init(&attr);
  467. if(ret) return althrd_error;
  468. if(type == almtx_recursive)
  469. {
  470. ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  471. #ifdef HAVE_PTHREAD_MUTEXATTR_SETKIND_NP
  472. if(ret != 0)
  473. ret = pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_RECURSIVE);
  474. #endif
  475. }
  476. else
  477. ret = 1;
  478. if(ret == 0)
  479. ret = pthread_mutex_init(mtx, &attr);
  480. pthread_mutexattr_destroy(&attr);
  481. }
  482. return ret ? althrd_error : althrd_success;
  483. }
  484. void almtx_destroy(almtx_t *mtx)
  485. {
  486. pthread_mutex_destroy(mtx);
  487. }
  488. int alcnd_init(alcnd_t *cond)
  489. {
  490. if(pthread_cond_init(cond, NULL) == 0)
  491. return althrd_success;
  492. return althrd_error;
  493. }
  494. int alcnd_signal(alcnd_t *cond)
  495. {
  496. if(pthread_cond_signal(cond) == 0)
  497. return althrd_success;
  498. return althrd_error;
  499. }
  500. int alcnd_broadcast(alcnd_t *cond)
  501. {
  502. if(pthread_cond_broadcast(cond) == 0)
  503. return althrd_success;
  504. return althrd_error;
  505. }
  506. int alcnd_wait(alcnd_t *cond, almtx_t *mtx)
  507. {
  508. if(pthread_cond_wait(cond, mtx) == 0)
  509. return althrd_success;
  510. return althrd_error;
  511. }
  512. void alcnd_destroy(alcnd_t *cond)
  513. {
  514. pthread_cond_destroy(cond);
  515. }
  516. int alsem_init(alsem_t *sem, unsigned int initial)
  517. {
  518. if(sem_init(sem, 0, initial) == 0)
  519. return althrd_success;
  520. return althrd_error;
  521. }
  522. void alsem_destroy(alsem_t *sem)
  523. {
  524. sem_destroy(sem);
  525. }
  526. int alsem_post(alsem_t *sem)
  527. {
  528. if(sem_post(sem) == 0)
  529. return althrd_success;
  530. return althrd_error;
  531. }
  532. int alsem_wait(alsem_t *sem)
  533. {
  534. if(sem_wait(sem) == 0) return althrd_success;
  535. if(errno == EINTR) return -2;
  536. return althrd_error;
  537. }
  538. int alsem_trywait(alsem_t *sem)
  539. {
  540. if(sem_trywait(sem) == 0) return althrd_success;
  541. if(errno == EWOULDBLOCK) return althrd_busy;
  542. if(errno == EINTR) return -2;
  543. return althrd_error;
  544. }
  545. int altss_create(altss_t *tss_id, altss_dtor_t callback)
  546. {
  547. if(pthread_key_create(tss_id, callback) != 0)
  548. return althrd_error;
  549. return althrd_success;
  550. }
  551. void altss_delete(altss_t tss_id)
  552. {
  553. pthread_key_delete(tss_id);
  554. }
  555. int altimespec_get(struct timespec *ts, int base)
  556. {
  557. if(base == AL_TIME_UTC)
  558. {
  559. int ret;
  560. #if _POSIX_TIMERS > 0
  561. ret = clock_gettime(CLOCK_REALTIME, ts);
  562. if(ret == 0) return base;
  563. #else /* _POSIX_TIMERS > 0 */
  564. struct timeval tv;
  565. ret = gettimeofday(&tv, NULL);
  566. if(ret == 0)
  567. {
  568. ts->tv_sec = tv.tv_sec;
  569. ts->tv_nsec = tv.tv_usec * 1000;
  570. return base;
  571. }
  572. #endif
  573. }
  574. return 0;
  575. }
  576. #endif
  577. void al_nssleep(unsigned long nsec)
  578. {
  579. struct timespec ts, rem;
  580. ts.tv_sec = nsec / 1000000000ul;
  581. ts.tv_nsec = nsec % 1000000000ul;
  582. while(althrd_sleep(&ts, &rem) == -1)
  583. ts = rem;
  584. }