2 * C11 <threads.h> emulation library
4 * (C) Copyright yohhoy 2012.
5 * Distributed under the Boost Software License, Version 1.0.
7 * Permission is hereby granted, free of charge, to any person or organization
8 * obtaining a copy of the software and accompanying documentation covered by
9 * this license (the "Software") to use, reproduce, display, distribute,
10 * execute, and transmit the Software, and to prepare [[derivative work]]s of the
11 * Software, and to permit third-parties to whom the Software is furnished to
12 * do so, all subject to the following:
14 * The copyright notices in the Software and this entire statement, including
15 * the above license grant, this restriction and the following disclaimer,
16 * must be included in all copies of the Software, in whole or in part, and
17 * all derivative works of the Software, unless such copies or derivative
18 * works are solely in the form of machine-executable object code generated by
19 * a source language processor.
21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
24 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
25 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
26 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27 * DEALINGS IN THE SOFTWARE.
32 #include <process.h> // MSVCRT
38 EMULATED_THREADS_USE_NATIVE_CALL_ONCE
39 Use native WindowsAPI one-time initialization function.
40 (requires WinVista or later)
41 Otherwise emulate by mtx_trylock() + *busy loop* for WinXP.
43 EMULATED_THREADS_USE_NATIVE_CV
44 Use native WindowsAPI condition variable object.
45 (requires WinVista or later)
46 Otherwise use emulated implementation for WinXP.
48 EMULATED_THREADS_TSS_DTOR_SLOTNUM
49 Max registerable TSS dtor number.
52 // XXX: Retain XP compatability
54 #if _WIN32_WINNT >= 0x0600
55 // Prefer native WindowsAPI on newer environment.
56 #if !defined(__MINGW32__)
57 #define EMULATED_THREADS_USE_NATIVE_CALL_ONCE
59 #define EMULATED_THREADS_USE_NATIVE_CV
62 #define EMULATED_THREADS_TSS_DTOR_SLOTNUM 64 // see TLS_MINIMUM_AVAILABLE
67 // check configuration
68 #if defined(EMULATED_THREADS_USE_NATIVE_CALL_ONCE) && (_WIN32_WINNT < 0x0600)
69 #error EMULATED_THREADS_USE_NATIVE_CALL_ONCE requires _WIN32_WINNT>=0x0600
72 #if defined(EMULATED_THREADS_USE_NATIVE_CV) && (_WIN32_WINNT < 0x0600)
73 #error EMULATED_THREADS_USE_NATIVE_CV requires _WIN32_WINNT>=0x0600
77 /*---------------------------- macros ----------------------------*/
78 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
79 #define ONCE_FLAG_INIT INIT_ONCE_STATIC_INIT
81 #define ONCE_FLAG_INIT {0}
83 #define TSS_DTOR_ITERATIONS 1
85 // FIXME: temporary non-standard hack to ease transition
86 #define _MTX_INITIALIZER_NP {(PCRITICAL_SECTION_DEBUG)-1, -1, 0, 0, 0, 0}
88 /*---------------------------- types ----------------------------*/
89 typedef struct cnd_t
{
90 #ifdef EMULATED_THREADS_USE_NATIVE_CV
91 CONDITION_VARIABLE condvar
;
98 CRITICAL_SECTION monitor
;
102 typedef HANDLE thrd_t
;
106 typedef CRITICAL_SECTION mtx_t
;
108 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
109 typedef INIT_ONCE once_flag
;
111 typedef struct once_flag_t
{
112 volatile LONG status
;
117 static inline void * tss_get(tss_t key
);
118 static inline void thrd_yield(void);
119 static inline int mtx_trylock(mtx_t
*mtx
);
120 static inline int mtx_lock(mtx_t
*mtx
);
121 static inline int mtx_unlock(mtx_t
*mtx
);
124 Implementation limits:
125 - Conditionally emulation for "Initialization functions"
126 (see EMULATED_THREADS_USE_NATIVE_CALL_ONCE macro)
127 - Emulated `mtx_timelock()' with mtx_trylock() + *busy loop*
129 static void impl_tss_dtor_invoke(void); // forward decl.
131 struct impl_thrd_param
{
136 static unsigned __stdcall
impl_thrd_routine(void *p
)
138 struct impl_thrd_param pack
;
140 memcpy(&pack
, p
, sizeof(struct impl_thrd_param
));
142 code
= pack
.func(pack
.arg
);
143 impl_tss_dtor_invoke();
144 return (unsigned)code
;
147 static DWORD
impl_xtime2msec(const xtime
*xt
)
149 return (DWORD
)((xt
->sec
* 1000U) + (xt
->nsec
/ 1000000L));
152 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
153 struct impl_call_once_param
{ void (*func
)(void); };
154 static BOOL CALLBACK
impl_call_once_callback(PINIT_ONCE InitOnce
, PVOID Parameter
, PVOID
*Context
)
156 struct impl_call_once_param
*param
= (struct impl_call_once_param
*)Parameter
;
158 ((void)InitOnce
); ((void)Context
); // suppress warning
161 #endif // ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
163 #ifndef EMULATED_THREADS_USE_NATIVE_CV
166 The implementation of condition variable is ported from Boost.Interprocess
167 See http://www.boost.org/boost/interprocess/sync/windows/condition.hpp
169 static void impl_cond_do_signal(cnd_t
*cond
, int broadcast
)
173 EnterCriticalSection(&cond
->monitor
);
174 if (cond
->to_unblock
!= 0) {
175 if (cond
->blocked
== 0) {
176 LeaveCriticalSection(&cond
->monitor
);
180 cond
->to_unblock
+= nsignal
= cond
->blocked
;
187 } else if (cond
->blocked
> cond
->gone
) {
188 WaitForSingleObject(cond
->sem_gate
, INFINITE
);
189 if (cond
->gone
!= 0) {
190 cond
->blocked
-= cond
->gone
;
194 nsignal
= cond
->to_unblock
= cond
->blocked
;
197 nsignal
= cond
->to_unblock
= 1;
201 LeaveCriticalSection(&cond
->monitor
);
204 ReleaseSemaphore(cond
->sem_queue
, nsignal
, NULL
);
207 static int impl_cond_do_wait(cnd_t
*cond
, mtx_t
*mtx
, const xtime
*xt
)
214 WaitForSingleObject(cond
->sem_gate
, INFINITE
);
216 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
220 w
= WaitForSingleObject(cond
->sem_queue
, xt
? impl_xtime2msec(xt
) : INFINITE
);
221 timeout
= (w
== WAIT_TIMEOUT
);
223 EnterCriticalSection(&cond
->monitor
);
224 if ((nleft
= cond
->to_unblock
) != 0) {
226 if (cond
->blocked
!= 0) {
232 if (--cond
->to_unblock
== 0) {
233 if (cond
->blocked
!= 0) {
234 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
237 else if ((ngone
= cond
->gone
) != 0) {
241 } else if (++cond
->gone
== INT_MAX
/2) {
242 WaitForSingleObject(cond
->sem_gate
, INFINITE
);
243 cond
->blocked
-= cond
->gone
;
244 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
247 LeaveCriticalSection(&cond
->monitor
);
251 WaitForSingleObject(cond
->sem_queue
, INFINITE
);
252 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
256 return timeout
? thrd_busy
: thrd_success
;
258 #endif // ifndef EMULATED_THREADS_USE_NATIVE_CV
260 static struct impl_tss_dtor_entry
{
263 } impl_tss_dtor_tbl
[EMULATED_THREADS_TSS_DTOR_SLOTNUM
];
265 static int impl_tss_dtor_register(tss_t key
, tss_dtor_t dtor
)
268 for (i
= 0; i
< EMULATED_THREADS_TSS_DTOR_SLOTNUM
; i
++) {
269 if (!impl_tss_dtor_tbl
[i
].dtor
)
272 if (i
== EMULATED_THREADS_TSS_DTOR_SLOTNUM
)
274 impl_tss_dtor_tbl
[i
].key
= key
;
275 impl_tss_dtor_tbl
[i
].dtor
= dtor
;
279 static void impl_tss_dtor_invoke()
282 for (i
= 0; i
< EMULATED_THREADS_TSS_DTOR_SLOTNUM
; i
++) {
283 if (impl_tss_dtor_tbl
[i
].dtor
) {
284 void* val
= tss_get(impl_tss_dtor_tbl
[i
].key
);
286 (impl_tss_dtor_tbl
[i
].dtor
)(val
);
292 /*--------------- 7.25.2 Initialization functions ---------------*/
295 call_once(once_flag
*flag
, void (*func
)(void))
297 assert(!flag
&& !func
);
298 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
300 struct impl_call_once_param param
;
302 InitOnceExecuteOnce(flag
, impl_call_once_callback
, (PVOID
)¶m
, NULL
);
305 if (InterlockedCompareExchange(&flag
->status
, 1, 0) == 0) {
307 InterlockedExchange(&flag
->status
, 2);
309 while (flag
->status
== 1) {
318 /*------------- 7.25.3 Condition variable functions -------------*/
321 cnd_broadcast(cnd_t
*cond
)
323 if (!cond
) return thrd_error
;
324 #ifdef EMULATED_THREADS_USE_NATIVE_CV
325 WakeAllConditionVariable(&cond
->condvar
);
327 impl_cond_do_signal(cond
, 1);
334 cnd_destroy(cnd_t
*cond
)
337 #ifdef EMULATED_THREADS_USE_NATIVE_CV
340 CloseHandle(cond
->sem_queue
);
341 CloseHandle(cond
->sem_gate
);
342 DeleteCriticalSection(&cond
->monitor
);
348 cnd_init(cnd_t
*cond
)
350 if (!cond
) return thrd_error
;
351 #ifdef EMULATED_THREADS_USE_NATIVE_CV
352 InitializeConditionVariable(&cond
->condvar
);
356 cond
->to_unblock
= 0;
357 cond
->sem_queue
= CreateSemaphore(NULL
, 0, LONG_MAX
, NULL
);
358 cond
->sem_gate
= CreateSemaphore(NULL
, 1, 1, NULL
);
359 InitializeCriticalSection(&cond
->monitor
);
366 cnd_signal(cnd_t
*cond
)
368 if (!cond
) return thrd_error
;
369 #ifdef EMULATED_THREADS_USE_NATIVE_CV
370 WakeConditionVariable(&cond
->condvar
);
372 impl_cond_do_signal(cond
, 0);
379 cnd_timedwait(cnd_t
*cond
, mtx_t
*mtx
, const xtime
*xt
)
381 if (!cond
|| !mtx
|| !xt
) return thrd_error
;
382 #ifdef EMULATED_THREADS_USE_NATIVE_CV
383 if (SleepConditionVariableCS(&cond
->condvar
, mtx
, impl_xtime2msec(xt
)))
385 return (GetLastError() == ERROR_TIMEOUT
) ? thrd_busy
: thrd_error
;
387 return impl_cond_do_wait(cond
, mtx
, xt
);
393 cnd_wait(cnd_t
*cond
, mtx_t
*mtx
)
395 if (!cond
|| !mtx
) return thrd_error
;
396 #ifdef EMULATED_THREADS_USE_NATIVE_CV
397 SleepConditionVariableCS(&cond
->condvar
, mtx
, INFINITE
);
399 impl_cond_do_wait(cond
, mtx
, NULL
);
405 /*-------------------- 7.25.4 Mutex functions --------------------*/
408 mtx_destroy(mtx_t
*mtx
)
411 DeleteCriticalSection(mtx
);
416 mtx_init(mtx_t
*mtx
, int type
)
418 if (!mtx
) return thrd_error
;
419 if (type
!= mtx_plain
&& type
!= mtx_timed
&& type
!= mtx_try
420 && type
!= (mtx_plain
|mtx_recursive
)
421 && type
!= (mtx_timed
|mtx_recursive
)
422 && type
!= (mtx_try
|mtx_recursive
))
424 InitializeCriticalSection(mtx
);
432 if (!mtx
) return thrd_error
;
433 EnterCriticalSection(mtx
);
439 mtx_timedlock(mtx_t
*mtx
, const xtime
*xt
)
442 if (!mtx
|| !xt
) return thrd_error
;
445 while (mtx_trylock(mtx
) != thrd_success
) {
457 mtx_trylock(mtx_t
*mtx
)
459 if (!mtx
) return thrd_error
;
460 return TryEnterCriticalSection(mtx
) ? thrd_success
: thrd_busy
;
465 mtx_unlock(mtx_t
*mtx
)
467 if (!mtx
) return thrd_error
;
468 LeaveCriticalSection(mtx
);
473 /*------------------- 7.25.5 Thread functions -------------------*/
476 thrd_create(thrd_t
*thr
, thrd_start_t func
, void *arg
)
478 struct impl_thrd_param
*pack
;
480 if (!thr
) return thrd_error
;
481 pack
= (struct impl_thrd_param
*)malloc(sizeof(struct impl_thrd_param
));
482 if (!pack
) return thrd_nomem
;
485 handle
= _beginthreadex(NULL
, 0, impl_thrd_routine
, pack
, 0, NULL
);
487 if (errno
== EAGAIN
|| errno
== EACCES
)
491 *thr
= (thrd_t
)handle
;
499 return GetCurrentThread();
504 thrd_detach(thrd_t thr
)
512 thrd_equal(thrd_t thr0
, thrd_t thr1
)
514 return (thr0
== thr1
);
521 impl_tss_dtor_invoke();
522 _endthreadex((unsigned)res
);
527 thrd_join(thrd_t thr
, int *res
)
530 w
= WaitForSingleObject(thr
, INFINITE
);
531 if (w
!= WAIT_OBJECT_0
)
534 if (!GetExitCodeThread(thr
, &code
)) {
546 thrd_sleep(const xtime
*xt
)
549 Sleep(impl_xtime2msec(xt
));
560 /*----------- 7.25.6 Thread-specific storage functions -----------*/
563 tss_create(tss_t
*key
, tss_dtor_t dtor
)
565 if (!key
) return thrd_error
;
568 if (impl_tss_dtor_register(*key
, dtor
)) {
573 return (*key
!= 0xFFFFFFFF) ? thrd_success
: thrd_error
;
578 tss_delete(tss_t key
)
587 return TlsGetValue(key
);
592 tss_set(tss_t key
, void *val
)
594 return TlsSetValue(key
, val
) ? thrd_success
: thrd_error
;
598 /*-------------------- 7.25.7 Time functions --------------------*/
601 xtime_get(xtime
*xt
, int base
)
604 if (base
== TIME_UTC
) {
605 xt
->sec
= time(NULL
);