threads.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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 && callback) callback(ptr);
  347. }
  348. UnlockUIntMapRead(&TlsDestructors);
  349. }
  350. #else
  351. #include <sys/time.h>
  352. #include <unistd.h>
  353. #include <pthread.h>
  354. #ifdef HAVE_PTHREAD_NP_H
  355. #include <pthread_np.h>
  356. #endif
  357. extern inline int althrd_sleep(const struct timespec *ts, struct timespec *rem);
  358. extern inline void alcall_once(alonce_flag *once, void (*callback)(void));
  359. extern inline void althrd_deinit(void);
  360. extern inline void althrd_thread_detach(void);
  361. void althrd_setname(althrd_t thr, const char *name)
  362. {
  363. #if defined(HAVE_PTHREAD_SETNAME_NP)
  364. #if defined(PTHREAD_SETNAME_NP_ONE_PARAM)
  365. if(althrd_equal(thr, althrd_current()))
  366. pthread_setname_np(name);
  367. #elif defined(PTHREAD_SETNAME_NP_THREE_PARAMS)
  368. pthread_setname_np(thr, "%s", (void*)name);
  369. #else
  370. pthread_setname_np(thr, name);
  371. #endif
  372. #elif defined(HAVE_PTHREAD_SET_NAME_NP)
  373. pthread_set_name_np(thr, name);
  374. #else
  375. (void)thr;
  376. (void)name;
  377. #endif
  378. }
  379. typedef struct thread_cntr {
  380. althrd_start_t func;
  381. void *arg;
  382. } thread_cntr;
  383. static void *althrd_starter(void *arg)
  384. {
  385. thread_cntr cntr;
  386. memcpy(&cntr, arg, sizeof(cntr));
  387. free(arg);
  388. return (void*)(intptr_t)((*cntr.func)(cntr.arg));
  389. }
  390. int althrd_create(althrd_t *thr, althrd_start_t func, void *arg)
  391. {
  392. thread_cntr *cntr;
  393. pthread_attr_t attr;
  394. size_t stackmult = 1;
  395. int err;
  396. cntr = malloc(sizeof(*cntr));
  397. if(!cntr) return althrd_nomem;
  398. if(pthread_attr_init(&attr) != 0)
  399. {
  400. free(cntr);
  401. return althrd_error;
  402. }
  403. retry_stacksize:
  404. if(pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE*stackmult) != 0)
  405. {
  406. pthread_attr_destroy(&attr);
  407. free(cntr);
  408. return althrd_error;
  409. }
  410. cntr->func = func;
  411. cntr->arg = arg;
  412. if((err=pthread_create(thr, &attr, althrd_starter, cntr)) == 0)
  413. {
  414. pthread_attr_destroy(&attr);
  415. return althrd_success;
  416. }
  417. if(err == EINVAL)
  418. {
  419. /* If an invalid stack size, try increasing it (limit x4, 8MB). */
  420. if(stackmult < 4)
  421. {
  422. stackmult *= 2;
  423. goto retry_stacksize;
  424. }
  425. /* If still nothing, try defaults and hope they're good enough. */
  426. if(pthread_create(thr, NULL, althrd_starter, cntr) == 0)
  427. {
  428. pthread_attr_destroy(&attr);
  429. return althrd_success;
  430. }
  431. }
  432. pthread_attr_destroy(&attr);
  433. free(cntr);
  434. return althrd_error;
  435. }
  436. int althrd_detach(althrd_t thr)
  437. {
  438. if(pthread_detach(thr) != 0)
  439. return althrd_error;
  440. return althrd_success;
  441. }
  442. int althrd_join(althrd_t thr, int *res)
  443. {
  444. void *code;
  445. if(pthread_join(thr, &code) != 0)
  446. return althrd_error;
  447. if(res != NULL)
  448. *res = (int)(intptr_t)code;
  449. return althrd_success;
  450. }
  451. int almtx_init(almtx_t *mtx, int type)
  452. {
  453. int ret;
  454. if(!mtx) return althrd_error;
  455. if((type&~almtx_recursive) != 0)
  456. return althrd_error;
  457. if(type == almtx_plain)
  458. ret = pthread_mutex_init(mtx, NULL);
  459. else
  460. {
  461. pthread_mutexattr_t attr;
  462. ret = pthread_mutexattr_init(&attr);
  463. if(ret) return althrd_error;
  464. if(type == almtx_recursive)
  465. {
  466. ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  467. #ifdef HAVE_PTHREAD_MUTEXATTR_SETKIND_NP
  468. if(ret != 0)
  469. ret = pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_RECURSIVE);
  470. #endif
  471. }
  472. else
  473. ret = 1;
  474. if(ret == 0)
  475. ret = pthread_mutex_init(mtx, &attr);
  476. pthread_mutexattr_destroy(&attr);
  477. }
  478. return ret ? althrd_error : althrd_success;
  479. }
  480. void almtx_destroy(almtx_t *mtx)
  481. {
  482. pthread_mutex_destroy(mtx);
  483. }
  484. int alcnd_init(alcnd_t *cond)
  485. {
  486. if(pthread_cond_init(cond, NULL) == 0)
  487. return althrd_success;
  488. return althrd_error;
  489. }
  490. int alcnd_signal(alcnd_t *cond)
  491. {
  492. if(pthread_cond_signal(cond) == 0)
  493. return althrd_success;
  494. return althrd_error;
  495. }
  496. int alcnd_broadcast(alcnd_t *cond)
  497. {
  498. if(pthread_cond_broadcast(cond) == 0)
  499. return althrd_success;
  500. return althrd_error;
  501. }
  502. int alcnd_wait(alcnd_t *cond, almtx_t *mtx)
  503. {
  504. if(pthread_cond_wait(cond, mtx) == 0)
  505. return althrd_success;
  506. return althrd_error;
  507. }
  508. void alcnd_destroy(alcnd_t *cond)
  509. {
  510. pthread_cond_destroy(cond);
  511. }
  512. int alsem_init(alsem_t *sem, unsigned int initial)
  513. {
  514. if(sem_init(sem, 0, initial) == 0)
  515. return althrd_success;
  516. return althrd_error;
  517. }
  518. void alsem_destroy(alsem_t *sem)
  519. {
  520. sem_destroy(sem);
  521. }
  522. int alsem_post(alsem_t *sem)
  523. {
  524. if(sem_post(sem) == 0)
  525. return althrd_success;
  526. return althrd_error;
  527. }
  528. int alsem_wait(alsem_t *sem)
  529. {
  530. if(sem_wait(sem) == 0) return althrd_success;
  531. if(errno == EINTR) return -2;
  532. return althrd_error;
  533. }
  534. int alsem_trywait(alsem_t *sem)
  535. {
  536. if(sem_trywait(sem) == 0) return althrd_success;
  537. if(errno == EWOULDBLOCK) return althrd_busy;
  538. if(errno == EINTR) return -2;
  539. return althrd_error;
  540. }
  541. int altss_create(altss_t *tss_id, altss_dtor_t callback)
  542. {
  543. if(pthread_key_create(tss_id, callback) != 0)
  544. return althrd_error;
  545. return althrd_success;
  546. }
  547. void altss_delete(altss_t tss_id)
  548. {
  549. pthread_key_delete(tss_id);
  550. }
  551. int altimespec_get(struct timespec *ts, int base)
  552. {
  553. if(base == AL_TIME_UTC)
  554. {
  555. int ret;
  556. #if _POSIX_TIMERS > 0
  557. ret = clock_gettime(CLOCK_REALTIME, ts);
  558. if(ret == 0) return base;
  559. #else /* _POSIX_TIMERS > 0 */
  560. struct timeval tv;
  561. ret = gettimeofday(&tv, NULL);
  562. if(ret == 0)
  563. {
  564. ts->tv_sec = tv.tv_sec;
  565. ts->tv_nsec = tv.tv_usec * 1000;
  566. return base;
  567. }
  568. #endif
  569. }
  570. return 0;
  571. }
  572. #endif
  573. void al_nssleep(unsigned long nsec)
  574. {
  575. struct timespec ts, rem;
  576. ts.tv_sec = nsec / 1000000000ul;
  577. ts.tv_nsec = nsec % 1000000000ul;
  578. while(althrd_sleep(&ts, &rem) == -1)
  579. ts = rem;
  580. }