tinycthread.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. /* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*-
  2. Copyright (c) 2012 Marcus Geelnard
  3. Copyright (c) 2013-2016 Evan Nemerson
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. */
  19. #include "tinycthread.h"
  20. #include <stdlib.h>
  21. /* Platform specific includes */
  22. #if defined(_TTHREAD_POSIX_)
  23. #include <signal.h>
  24. #include <sched.h>
  25. #include <unistd.h>
  26. #include <sys/time.h>
  27. #include <errno.h>
  28. #elif defined(_TTHREAD_WIN32_)
  29. #include <process.h>
  30. #include <sys/timeb.h>
  31. #endif
  32. /* Standard, good-to-have defines */
  33. #ifndef NULL
  34. #define NULL (void*)0
  35. #endif
  36. #ifndef TRUE
  37. #define TRUE 1
  38. #endif
  39. #ifndef FALSE
  40. #define FALSE 0
  41. #endif
  42. #ifdef __cplusplus
  43. extern "C" {
  44. #endif
  45. int mtx_init(mtx_t *mtx, int type)
  46. {
  47. #if defined(_TTHREAD_WIN32_)
  48. mtx->mAlreadyLocked = FALSE;
  49. mtx->mRecursive = type & mtx_recursive;
  50. mtx->mTimed = type & mtx_timed;
  51. if (!mtx->mTimed)
  52. {
  53. InitializeCriticalSection(&(mtx->mHandle.cs));
  54. }
  55. else
  56. {
  57. mtx->mHandle.mut = CreateMutex(NULL, FALSE, NULL);
  58. if (mtx->mHandle.mut == NULL)
  59. {
  60. return thrd_error;
  61. }
  62. }
  63. return thrd_success;
  64. #else
  65. int ret;
  66. pthread_mutexattr_t attr;
  67. pthread_mutexattr_init(&attr);
  68. if (type & mtx_recursive)
  69. {
  70. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  71. }
  72. ret = pthread_mutex_init(mtx, &attr);
  73. pthread_mutexattr_destroy(&attr);
  74. return ret == 0 ? thrd_success : thrd_error;
  75. #endif
  76. }
  77. void mtx_destroy(mtx_t *mtx)
  78. {
  79. #if defined(_TTHREAD_WIN32_)
  80. if (!mtx->mTimed)
  81. {
  82. DeleteCriticalSection(&(mtx->mHandle.cs));
  83. }
  84. else
  85. {
  86. CloseHandle(mtx->mHandle.mut);
  87. }
  88. #else
  89. pthread_mutex_destroy(mtx);
  90. #endif
  91. }
  92. int mtx_lock(mtx_t *mtx)
  93. {
  94. #if defined(_TTHREAD_WIN32_)
  95. if (!mtx->mTimed)
  96. {
  97. EnterCriticalSection(&(mtx->mHandle.cs));
  98. }
  99. else
  100. {
  101. switch (WaitForSingleObject(mtx->mHandle.mut, INFINITE))
  102. {
  103. case WAIT_OBJECT_0:
  104. break;
  105. case WAIT_ABANDONED:
  106. default:
  107. return thrd_error;
  108. }
  109. }
  110. if (!mtx->mRecursive)
  111. {
  112. while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */
  113. mtx->mAlreadyLocked = TRUE;
  114. }
  115. return thrd_success;
  116. #else
  117. return pthread_mutex_lock(mtx) == 0 ? thrd_success : thrd_error;
  118. #endif
  119. }
  120. int mtx_timedlock(mtx_t *mtx, const struct timespec *ts)
  121. {
  122. #if defined(_TTHREAD_WIN32_)
  123. struct timespec current_ts;
  124. DWORD timeoutMs;
  125. if (!mtx->mTimed)
  126. {
  127. return thrd_error;
  128. }
  129. timespec_get(&current_ts, TIME_UTC);
  130. if ((current_ts.tv_sec > ts->tv_sec) || ((current_ts.tv_sec == ts->tv_sec) && (current_ts.tv_nsec >= ts->tv_nsec)))
  131. {
  132. timeoutMs = 0;
  133. }
  134. else
  135. {
  136. timeoutMs = (DWORD)(ts->tv_sec - current_ts.tv_sec) * 1000;
  137. timeoutMs += (ts->tv_nsec - current_ts.tv_nsec) / 1000000;
  138. timeoutMs += 1;
  139. }
  140. /* TODO: the timeout for WaitForSingleObject doesn't include time
  141. while the computer is asleep. */
  142. switch (WaitForSingleObject(mtx->mHandle.mut, timeoutMs))
  143. {
  144. case WAIT_OBJECT_0:
  145. break;
  146. case WAIT_TIMEOUT:
  147. return thrd_timedout;
  148. case WAIT_ABANDONED:
  149. default:
  150. return thrd_error;
  151. }
  152. if (!mtx->mRecursive)
  153. {
  154. while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */
  155. mtx->mAlreadyLocked = TRUE;
  156. }
  157. return thrd_success;
  158. #elif defined(_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS >= 200112L) && defined(_POSIX_THREADS) && (_POSIX_THREADS >= 200112L)
  159. switch (pthread_mutex_timedlock(mtx, ts)) {
  160. case 0:
  161. return thrd_success;
  162. case ETIMEDOUT:
  163. return thrd_timedout;
  164. default:
  165. return thrd_error;
  166. }
  167. #else
  168. int rc;
  169. struct timespec cur, dur;
  170. /* Try to acquire the lock and, if we fail, sleep for 5ms. */
  171. while ((rc = pthread_mutex_trylock (mtx)) == EBUSY) {
  172. timespec_get(&cur, TIME_UTC);
  173. if ((cur.tv_sec > ts->tv_sec) || ((cur.tv_sec == ts->tv_sec) && (cur.tv_nsec >= ts->tv_nsec)))
  174. {
  175. break;
  176. }
  177. dur.tv_sec = ts->tv_sec - cur.tv_sec;
  178. dur.tv_nsec = ts->tv_nsec - cur.tv_nsec;
  179. if (dur.tv_nsec < 0)
  180. {
  181. dur.tv_sec--;
  182. dur.tv_nsec += 1000000000;
  183. }
  184. if ((dur.tv_sec != 0) || (dur.tv_nsec > 5000000))
  185. {
  186. dur.tv_sec = 0;
  187. dur.tv_nsec = 5000000;
  188. }
  189. nanosleep(&dur, NULL);
  190. }
  191. switch (rc) {
  192. case 0:
  193. return thrd_success;
  194. case ETIMEDOUT:
  195. case EBUSY:
  196. return thrd_timedout;
  197. default:
  198. return thrd_error;
  199. }
  200. #endif
  201. }
  202. int mtx_trylock(mtx_t *mtx)
  203. {
  204. #if defined(_TTHREAD_WIN32_)
  205. int ret;
  206. if (!mtx->mTimed)
  207. {
  208. ret = TryEnterCriticalSection(&(mtx->mHandle.cs)) ? thrd_success : thrd_busy;
  209. }
  210. else
  211. {
  212. ret = (WaitForSingleObject(mtx->mHandle.mut, 0) == WAIT_OBJECT_0) ? thrd_success : thrd_busy;
  213. }
  214. if ((!mtx->mRecursive) && (ret == thrd_success))
  215. {
  216. if (mtx->mAlreadyLocked)
  217. {
  218. LeaveCriticalSection(&(mtx->mHandle.cs));
  219. ret = thrd_busy;
  220. }
  221. else
  222. {
  223. mtx->mAlreadyLocked = TRUE;
  224. }
  225. }
  226. return ret;
  227. #else
  228. return (pthread_mutex_trylock(mtx) == 0) ? thrd_success : thrd_busy;
  229. #endif
  230. }
  231. int mtx_unlock(mtx_t *mtx)
  232. {
  233. #if defined(_TTHREAD_WIN32_)
  234. mtx->mAlreadyLocked = FALSE;
  235. if (!mtx->mTimed)
  236. {
  237. LeaveCriticalSection(&(mtx->mHandle.cs));
  238. }
  239. else
  240. {
  241. if (!ReleaseMutex(mtx->mHandle.mut))
  242. {
  243. return thrd_error;
  244. }
  245. }
  246. return thrd_success;
  247. #else
  248. return pthread_mutex_unlock(mtx) == 0 ? thrd_success : thrd_error;;
  249. #endif
  250. }
  251. #if defined(_TTHREAD_WIN32_)
  252. #define _CONDITION_EVENT_ONE 0
  253. #define _CONDITION_EVENT_ALL 1
  254. #endif
  255. int cnd_init(cnd_t *cond)
  256. {
  257. #if defined(_TTHREAD_WIN32_)
  258. cond->mWaitersCount = 0;
  259. /* Init critical section */
  260. InitializeCriticalSection(&cond->mWaitersCountLock);
  261. /* Init events */
  262. cond->mEvents[_CONDITION_EVENT_ONE] = CreateEvent(NULL, FALSE, FALSE, NULL);
  263. if (cond->mEvents[_CONDITION_EVENT_ONE] == NULL)
  264. {
  265. cond->mEvents[_CONDITION_EVENT_ALL] = NULL;
  266. return thrd_error;
  267. }
  268. cond->mEvents[_CONDITION_EVENT_ALL] = CreateEvent(NULL, TRUE, FALSE, NULL);
  269. if (cond->mEvents[_CONDITION_EVENT_ALL] == NULL)
  270. {
  271. CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]);
  272. cond->mEvents[_CONDITION_EVENT_ONE] = NULL;
  273. return thrd_error;
  274. }
  275. return thrd_success;
  276. #else
  277. return pthread_cond_init(cond, NULL) == 0 ? thrd_success : thrd_error;
  278. #endif
  279. }
  280. void cnd_destroy(cnd_t *cond)
  281. {
  282. #if defined(_TTHREAD_WIN32_)
  283. if (cond->mEvents[_CONDITION_EVENT_ONE] != NULL)
  284. {
  285. CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]);
  286. }
  287. if (cond->mEvents[_CONDITION_EVENT_ALL] != NULL)
  288. {
  289. CloseHandle(cond->mEvents[_CONDITION_EVENT_ALL]);
  290. }
  291. DeleteCriticalSection(&cond->mWaitersCountLock);
  292. #else
  293. pthread_cond_destroy(cond);
  294. #endif
  295. }
  296. int cnd_signal(cnd_t *cond)
  297. {
  298. #if defined(_TTHREAD_WIN32_)
  299. int haveWaiters;
  300. /* Are there any waiters? */
  301. EnterCriticalSection(&cond->mWaitersCountLock);
  302. haveWaiters = (cond->mWaitersCount > 0);
  303. LeaveCriticalSection(&cond->mWaitersCountLock);
  304. /* If we have any waiting threads, send them a signal */
  305. if(haveWaiters)
  306. {
  307. if (SetEvent(cond->mEvents[_CONDITION_EVENT_ONE]) == 0)
  308. {
  309. return thrd_error;
  310. }
  311. }
  312. return thrd_success;
  313. #else
  314. return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error;
  315. #endif
  316. }
  317. int cnd_broadcast(cnd_t *cond)
  318. {
  319. #if defined(_TTHREAD_WIN32_)
  320. int haveWaiters;
  321. /* Are there any waiters? */
  322. EnterCriticalSection(&cond->mWaitersCountLock);
  323. haveWaiters = (cond->mWaitersCount > 0);
  324. LeaveCriticalSection(&cond->mWaitersCountLock);
  325. /* If we have any waiting threads, send them a signal */
  326. if(haveWaiters)
  327. {
  328. if (SetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0)
  329. {
  330. return thrd_error;
  331. }
  332. }
  333. return thrd_success;
  334. #else
  335. return pthread_cond_broadcast(cond) == 0 ? thrd_success : thrd_error;
  336. #endif
  337. }
  338. #if defined(_TTHREAD_WIN32_)
  339. static int _cnd_timedwait_win32(cnd_t *cond, mtx_t *mtx, DWORD timeout)
  340. {
  341. DWORD result;
  342. int lastWaiter;
  343. /* Increment number of waiters */
  344. EnterCriticalSection(&cond->mWaitersCountLock);
  345. ++ cond->mWaitersCount;
  346. LeaveCriticalSection(&cond->mWaitersCountLock);
  347. /* Release the mutex while waiting for the condition (will decrease
  348. the number of waiters when done)... */
  349. mtx_unlock(mtx);
  350. /* Wait for either event to become signaled due to cnd_signal() or
  351. cnd_broadcast() being called */
  352. result = WaitForMultipleObjects(2, cond->mEvents, FALSE, timeout);
  353. if (result == WAIT_TIMEOUT)
  354. {
  355. /* The mutex is locked again before the function returns, even if an error occurred */
  356. mtx_lock(mtx);
  357. return thrd_timedout;
  358. }
  359. else if (result == WAIT_FAILED)
  360. {
  361. /* The mutex is locked again before the function returns, even if an error occurred */
  362. mtx_lock(mtx);
  363. return thrd_error;
  364. }
  365. /* Check if we are the last waiter */
  366. EnterCriticalSection(&cond->mWaitersCountLock);
  367. -- cond->mWaitersCount;
  368. lastWaiter = (result == (WAIT_OBJECT_0 + _CONDITION_EVENT_ALL)) &&
  369. (cond->mWaitersCount == 0);
  370. LeaveCriticalSection(&cond->mWaitersCountLock);
  371. /* If we are the last waiter to be notified to stop waiting, reset the event */
  372. if (lastWaiter)
  373. {
  374. if (ResetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0)
  375. {
  376. /* The mutex is locked again before the function returns, even if an error occurred */
  377. mtx_lock(mtx);
  378. return thrd_error;
  379. }
  380. }
  381. /* Re-acquire the mutex */
  382. mtx_lock(mtx);
  383. return thrd_success;
  384. }
  385. #endif
  386. int cnd_wait(cnd_t *cond, mtx_t *mtx)
  387. {
  388. #if defined(_TTHREAD_WIN32_)
  389. return _cnd_timedwait_win32(cond, mtx, INFINITE);
  390. #else
  391. return pthread_cond_wait(cond, mtx) == 0 ? thrd_success : thrd_error;
  392. #endif
  393. }
  394. int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts)
  395. {
  396. #if defined(_TTHREAD_WIN32_)
  397. struct timespec now;
  398. if (timespec_get(&now, TIME_UTC) == TIME_UTC)
  399. {
  400. unsigned long long nowInMilliseconds = now.tv_sec * 1000 + now.tv_nsec / 1000000;
  401. unsigned long long tsInMilliseconds = ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
  402. DWORD delta = (tsInMilliseconds > nowInMilliseconds) ?
  403. (DWORD)(tsInMilliseconds - nowInMilliseconds) : 0;
  404. return _cnd_timedwait_win32(cond, mtx, delta);
  405. }
  406. else
  407. return thrd_error;
  408. #else
  409. int ret;
  410. ret = pthread_cond_timedwait(cond, mtx, ts);
  411. if (ret == ETIMEDOUT)
  412. {
  413. return thrd_timedout;
  414. }
  415. return ret == 0 ? thrd_success : thrd_error;
  416. #endif
  417. }
  418. #if defined(_TTHREAD_WIN32_)
  419. struct TinyCThreadTSSData {
  420. void* value;
  421. tss_t key;
  422. struct TinyCThreadTSSData* next;
  423. };
  424. static tss_dtor_t _tinycthread_tss_dtors[1088] = { NULL, };
  425. static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_head = NULL;
  426. static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_tail = NULL;
  427. static void _tinycthread_tss_cleanup (void);
  428. static void _tinycthread_tss_cleanup (void) {
  429. struct TinyCThreadTSSData* data;
  430. int iteration;
  431. unsigned int again = 1;
  432. void* value;
  433. for (iteration = 0 ; iteration < TSS_DTOR_ITERATIONS && again > 0 ; iteration++)
  434. {
  435. again = 0;
  436. for (data = _tinycthread_tss_head ; data != NULL ; data = data->next)
  437. {
  438. if (data->value != NULL)
  439. {
  440. value = data->value;
  441. data->value = NULL;
  442. if (_tinycthread_tss_dtors[data->key] != NULL)
  443. {
  444. again = 1;
  445. _tinycthread_tss_dtors[data->key](value);
  446. }
  447. }
  448. }
  449. }
  450. while (_tinycthread_tss_head != NULL) {
  451. data = _tinycthread_tss_head->next;
  452. free (_tinycthread_tss_head);
  453. _tinycthread_tss_head = data;
  454. }
  455. _tinycthread_tss_head = NULL;
  456. _tinycthread_tss_tail = NULL;
  457. }
  458. static void NTAPI _tinycthread_tss_callback(PVOID h, DWORD dwReason, PVOID pv)
  459. {
  460. (void)h;
  461. (void)pv;
  462. if (_tinycthread_tss_head != NULL && (dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH))
  463. {
  464. _tinycthread_tss_cleanup();
  465. }
  466. }
  467. #if defined(_MSC_VER)
  468. #ifdef _M_X64
  469. #pragma const_seg(".CRT$XLB")
  470. #else
  471. #pragma data_seg(".CRT$XLB")
  472. #endif
  473. PIMAGE_TLS_CALLBACK p_thread_callback = _tinycthread_tss_callback;
  474. #ifdef _M_X64
  475. #pragma data_seg()
  476. #else
  477. #pragma const_seg()
  478. #endif
  479. #else
  480. PIMAGE_TLS_CALLBACK p_thread_callback __attribute__((section(".CRT$XLB"))) = _tinycthread_tss_callback;
  481. #endif
  482. #endif /* defined(_TTHREAD_WIN32_) */
  483. /** Information to pass to the new thread (what to run). */
  484. typedef struct {
  485. thrd_start_t mFunction; /**< Pointer to the function to be executed. */
  486. void * mArg; /**< Function argument for the thread function. */
  487. } _thread_start_info;
  488. /* Thread wrapper function. */
  489. #if defined(_TTHREAD_WIN32_)
  490. static DWORD WINAPI _thrd_wrapper_function(LPVOID aArg)
  491. #elif defined(_TTHREAD_POSIX_)
  492. static void * _thrd_wrapper_function(void * aArg)
  493. #endif
  494. {
  495. thrd_start_t fun;
  496. void *arg;
  497. int res;
  498. /* Get thread startup information */
  499. _thread_start_info *ti = (_thread_start_info *) aArg;
  500. fun = ti->mFunction;
  501. arg = ti->mArg;
  502. /* The thread is responsible for freeing the startup information */
  503. free((void *)ti);
  504. /* Call the actual client thread function */
  505. res = fun(arg);
  506. #if defined(_TTHREAD_WIN32_)
  507. if (_tinycthread_tss_head != NULL)
  508. {
  509. _tinycthread_tss_cleanup();
  510. }
  511. return (DWORD)res;
  512. #else
  513. return (void*)(intptr_t)res;
  514. #endif
  515. }
  516. int thrd_create(thrd_t *thr, thrd_start_t func, void *arg)
  517. {
  518. /* Fill out the thread startup information (passed to the thread wrapper,
  519. which will eventually free it) */
  520. _thread_start_info* ti = (_thread_start_info*)malloc(sizeof(_thread_start_info));
  521. if (ti == NULL)
  522. {
  523. return thrd_nomem;
  524. }
  525. ti->mFunction = func;
  526. ti->mArg = arg;
  527. /* Create the thread */
  528. #if defined(_TTHREAD_WIN32_)
  529. *thr = CreateThread(NULL, 0, _thrd_wrapper_function, (LPVOID) ti, 0, NULL);
  530. #elif defined(_TTHREAD_POSIX_)
  531. if(pthread_create(thr, NULL, _thrd_wrapper_function, (void *)ti) != 0)
  532. {
  533. *thr = 0;
  534. }
  535. #endif
  536. /* Did we fail to create the thread? */
  537. if(!*thr)
  538. {
  539. free(ti);
  540. return thrd_error;
  541. }
  542. return thrd_success;
  543. }
  544. thrd_t thrd_current(void)
  545. {
  546. #if defined(_TTHREAD_WIN32_)
  547. return GetCurrentThread();
  548. #else
  549. return pthread_self();
  550. #endif
  551. }
  552. int thrd_detach(thrd_t thr)
  553. {
  554. #if defined(_TTHREAD_WIN32_)
  555. /* https://stackoverflow.com/questions/12744324/how-to-detach-a-thread-on-windows-c#answer-12746081 */
  556. return CloseHandle(thr) != 0 ? thrd_success : thrd_error;
  557. #else
  558. return pthread_detach(thr) == 0 ? thrd_success : thrd_error;
  559. #endif
  560. }
  561. int thrd_equal(thrd_t thr0, thrd_t thr1)
  562. {
  563. #if defined(_TTHREAD_WIN32_)
  564. return GetThreadId(thr0) == GetThreadId(thr1);
  565. #else
  566. return pthread_equal(thr0, thr1);
  567. #endif
  568. }
  569. void thrd_exit(int res)
  570. {
  571. #if defined(_TTHREAD_WIN32_)
  572. if (_tinycthread_tss_head != NULL)
  573. {
  574. _tinycthread_tss_cleanup();
  575. }
  576. ExitThread((DWORD)res);
  577. #else
  578. pthread_exit((void*)(intptr_t)res);
  579. #endif
  580. }
  581. int thrd_join(thrd_t thr, int *res)
  582. {
  583. #if defined(_TTHREAD_WIN32_)
  584. DWORD dwRes;
  585. if (WaitForSingleObject(thr, INFINITE) == WAIT_FAILED)
  586. {
  587. return thrd_error;
  588. }
  589. if (res != NULL)
  590. {
  591. if (GetExitCodeThread(thr, &dwRes) != 0)
  592. {
  593. *res = (int) dwRes;
  594. }
  595. else
  596. {
  597. return thrd_error;
  598. }
  599. }
  600. CloseHandle(thr);
  601. #elif defined(_TTHREAD_POSIX_)
  602. void *pres;
  603. if (pthread_join(thr, &pres) != 0)
  604. {
  605. return thrd_error;
  606. }
  607. if (res != NULL)
  608. {
  609. *res = (int)(intptr_t)pres;
  610. }
  611. #endif
  612. return thrd_success;
  613. }
  614. int thrd_sleep(const struct timespec *duration, struct timespec *remaining)
  615. {
  616. #if !defined(_TTHREAD_WIN32_)
  617. int res = nanosleep(duration, remaining);
  618. if (res == 0) {
  619. return 0;
  620. } else if (errno == EINTR) {
  621. return -1;
  622. } else {
  623. return -2;
  624. }
  625. #else
  626. struct timespec start;
  627. DWORD t;
  628. timespec_get(&start, TIME_UTC);
  629. t = SleepEx((DWORD)(duration->tv_sec * 1000 +
  630. duration->tv_nsec / 1000000 +
  631. (((duration->tv_nsec % 1000000) == 0) ? 0 : 1)),
  632. TRUE);
  633. if (t == 0) {
  634. return 0;
  635. } else {
  636. if (remaining != NULL) {
  637. timespec_get(remaining, TIME_UTC);
  638. remaining->tv_sec -= start.tv_sec;
  639. remaining->tv_nsec -= start.tv_nsec;
  640. if (remaining->tv_nsec < 0)
  641. {
  642. remaining->tv_nsec += 1000000000;
  643. remaining->tv_sec -= 1;
  644. }
  645. }
  646. return (t == WAIT_IO_COMPLETION) ? -1 : -2;
  647. }
  648. #endif
  649. }
  650. void thrd_yield(void)
  651. {
  652. #if defined(_TTHREAD_WIN32_)
  653. Sleep(0);
  654. #else
  655. sched_yield();
  656. #endif
  657. }
  658. int tss_create(tss_t *key, tss_dtor_t dtor)
  659. {
  660. #if defined(_TTHREAD_WIN32_)
  661. *key = TlsAlloc();
  662. if (*key == TLS_OUT_OF_INDEXES)
  663. {
  664. return thrd_error;
  665. }
  666. _tinycthread_tss_dtors[*key] = dtor;
  667. #else
  668. if (pthread_key_create(key, dtor) != 0)
  669. {
  670. return thrd_error;
  671. }
  672. #endif
  673. return thrd_success;
  674. }
  675. void tss_delete(tss_t key)
  676. {
  677. #if defined(_TTHREAD_WIN32_)
  678. struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*) TlsGetValue (key);
  679. struct TinyCThreadTSSData* prev = NULL;
  680. if (data != NULL)
  681. {
  682. if (data == _tinycthread_tss_head)
  683. {
  684. _tinycthread_tss_head = data->next;
  685. }
  686. else
  687. {
  688. prev = _tinycthread_tss_head;
  689. if (prev != NULL)
  690. {
  691. while (prev->next != data)
  692. {
  693. prev = prev->next;
  694. }
  695. }
  696. }
  697. if (data == _tinycthread_tss_tail)
  698. {
  699. _tinycthread_tss_tail = prev;
  700. }
  701. free (data);
  702. }
  703. _tinycthread_tss_dtors[key] = NULL;
  704. TlsFree(key);
  705. #else
  706. pthread_key_delete(key);
  707. #endif
  708. }
  709. void *tss_get(tss_t key)
  710. {
  711. #if defined(_TTHREAD_WIN32_)
  712. struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key);
  713. if (data == NULL)
  714. {
  715. return NULL;
  716. }
  717. return data->value;
  718. #else
  719. return pthread_getspecific(key);
  720. #endif
  721. }
  722. int tss_set(tss_t key, void *val)
  723. {
  724. #if defined(_TTHREAD_WIN32_)
  725. struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key);
  726. if (data == NULL)
  727. {
  728. data = (struct TinyCThreadTSSData*)malloc(sizeof(struct TinyCThreadTSSData));
  729. if (data == NULL)
  730. {
  731. return thrd_error;
  732. }
  733. data->value = NULL;
  734. data->key = key;
  735. data->next = NULL;
  736. if (_tinycthread_tss_tail != NULL)
  737. {
  738. _tinycthread_tss_tail->next = data;
  739. }
  740. else
  741. {
  742. _tinycthread_tss_tail = data;
  743. }
  744. if (_tinycthread_tss_head == NULL)
  745. {
  746. _tinycthread_tss_head = data;
  747. }
  748. if (!TlsSetValue(key, data))
  749. {
  750. free (data);
  751. return thrd_error;
  752. }
  753. }
  754. data->value = val;
  755. #else
  756. if (pthread_setspecific(key, val) != 0)
  757. {
  758. return thrd_error;
  759. }
  760. #endif
  761. return thrd_success;
  762. }
  763. #if defined(_TTHREAD_EMULATE_TIMESPEC_GET_)
  764. int _tthread_timespec_get(struct timespec *ts, int base)
  765. {
  766. #if defined(_TTHREAD_WIN32_)
  767. struct _timeb tb;
  768. #elif !defined(CLOCK_REALTIME)
  769. struct timeval tv;
  770. #endif
  771. if (base != TIME_UTC)
  772. {
  773. return 0;
  774. }
  775. #if defined(_TTHREAD_WIN32_)
  776. _ftime_s(&tb);
  777. ts->tv_sec = (time_t)tb.time;
  778. ts->tv_nsec = 1000000L * (long)tb.millitm;
  779. #elif defined(CLOCK_REALTIME)
  780. base = (clock_gettime(CLOCK_REALTIME, ts) == 0) ? base : 0;
  781. #else
  782. gettimeofday(&tv, NULL);
  783. ts->tv_sec = (time_t)tv.tv_sec;
  784. ts->tv_nsec = 1000L * (long)tv.tv_usec;
  785. #endif
  786. return base;
  787. }
  788. #endif /* _TTHREAD_EMULATE_TIMESPEC_GET_ */
  789. #if defined(_TTHREAD_WIN32_)
  790. void call_once(once_flag *flag, void (*func)(void))
  791. {
  792. /* The idea here is that we use a spin lock (via the
  793. InterlockedCompareExchange function) to restrict access to the
  794. critical section until we have initialized it, then we use the
  795. critical section to block until the callback has completed
  796. execution. */
  797. while (flag->status < 3)
  798. {
  799. switch (flag->status)
  800. {
  801. case 0:
  802. if (InterlockedCompareExchange (&(flag->status), 1, 0) == 0) {
  803. InitializeCriticalSection(&(flag->lock));
  804. EnterCriticalSection(&(flag->lock));
  805. flag->status = 2;
  806. func();
  807. flag->status = 3;
  808. LeaveCriticalSection(&(flag->lock));
  809. return;
  810. }
  811. break;
  812. case 1:
  813. break;
  814. case 2:
  815. EnterCriticalSection(&(flag->lock));
  816. LeaveCriticalSection(&(flag->lock));
  817. break;
  818. }
  819. }
  820. }
  821. #endif /* defined(_TTHREAD_WIN32_) */
  822. #ifdef __cplusplus
  823. }
  824. #endif