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
37 EMULATED_THREADS_USE_NATIVE_CALL_ONCE
38 Use native WindowsAPI one-time initialization function.
39 (requires WinVista or later)
40 Otherwise emulate by mtx_trylock() + *busy loop* for WinXP.
42 EMULATED_THREADS_USE_NATIVE_CV
43 Use native WindowsAPI condition variable object.
44 (requires WinVista or later)
45 Otherwise use emulated implementation for WinXP.
47 EMULATED_THREADS_TSS_DTOR_SLOTNUM
48 Max registerable TSS dtor number.
51 // XXX: Retain XP compatability
53 #if _WIN32_WINNT >= 0x0600
54 // Prefer native WindowsAPI on newer environment.
55 #if !defined(__MINGW32__)
56 #define EMULATED_THREADS_USE_NATIVE_CALL_ONCE
58 #define EMULATED_THREADS_USE_NATIVE_CV
61 #define EMULATED_THREADS_TSS_DTOR_SLOTNUM 64 // see TLS_MINIMUM_AVAILABLE
66 // check configuration
67 #if defined(EMULATED_THREADS_USE_NATIVE_CALL_ONCE) && (_WIN32_WINNT < 0x0600)
68 #error EMULATED_THREADS_USE_NATIVE_CALL_ONCE requires _WIN32_WINNT>=0x0600
71 #if defined(EMULATED_THREADS_USE_NATIVE_CV) && (_WIN32_WINNT < 0x0600)
72 #error EMULATED_THREADS_USE_NATIVE_CV requires _WIN32_WINNT>=0x0600
76 /*---------------------------- macros ----------------------------*/
77 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
78 #define ONCE_FLAG_INIT INIT_ONCE_STATIC_INIT
80 #define ONCE_FLAG_INIT {0}
82 #define TSS_DTOR_ITERATIONS 1
84 // FIXME: temporary non-standard hack to ease transition
85 #define _MTX_INITIALIZER_NP {(PCRITICAL_SECTION_DEBUG)-1, -1, 0, 0, 0, 0}
87 /*---------------------------- types ----------------------------*/
88 typedef struct cnd_t
{
89 #ifdef EMULATED_THREADS_USE_NATIVE_CV
90 CONDITION_VARIABLE condvar
;
97 CRITICAL_SECTION monitor
;
101 typedef HANDLE thrd_t
;
105 typedef CRITICAL_SECTION mtx_t
;
107 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
108 typedef INIT_ONCE once_flag
;
110 typedef struct once_flag_t
{
111 volatile LONG status
;
116 static inline void * tss_get(tss_t key
);
117 static inline void thrd_yield(void);
118 static inline int mtx_trylock(mtx_t
*mtx
);
119 static inline int mtx_lock(mtx_t
*mtx
);
120 static inline int mtx_unlock(mtx_t
*mtx
);
123 Implementation limits:
124 - Conditionally emulation for "Initialization functions"
125 (see EMULATED_THREADS_USE_NATIVE_CALL_ONCE macro)
126 - Emulated `mtx_timelock()' with mtx_trylock() + *busy loop*
128 static void impl_tss_dtor_invoke(void); // forward decl.
130 struct impl_thrd_param
{
135 static unsigned __stdcall
impl_thrd_routine(void *p
)
137 struct impl_thrd_param pack
;
139 memcpy(&pack
, p
, sizeof(struct impl_thrd_param
));
141 code
= pack
.func(pack
.arg
);
142 impl_tss_dtor_invoke();
143 return (unsigned)code
;
146 static DWORD
impl_xtime2msec(const xtime
*xt
)
148 return (DWORD
)((xt
->sec
* 1000u) + (xt
->nsec
/ 1000));
151 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
152 struct impl_call_once_param
{ void (*func
)(void); };
153 static BOOL CALLBACK
impl_call_once_callback(PINIT_ONCE InitOnce
, PVOID Parameter
, PVOID
*Context
)
155 struct impl_call_once_param
*param
= (struct impl_call_once_param
*)Parameter
;
157 ((void)InitOnce
); ((void)Context
); // suppress warning
160 #endif // ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
162 #ifndef EMULATED_THREADS_USE_NATIVE_CV
165 The implementation of condition variable is ported from Boost.Interprocess
166 See http://www.boost.org/boost/interprocess/sync/windows/condition.hpp
168 static void impl_cond_do_signal(cnd_t
*cond
, int broadcast
)
172 EnterCriticalSection(&cond
->monitor
);
173 if (cond
->to_unblock
!= 0) {
174 if (cond
->blocked
== 0) {
175 LeaveCriticalSection(&cond
->monitor
);
179 cond
->to_unblock
+= nsignal
= cond
->blocked
;
186 } else if (cond
->blocked
> cond
->gone
) {
187 WaitForSingleObject(cond
->sem_gate
, INFINITE
);
188 if (cond
->gone
!= 0) {
189 cond
->blocked
-= cond
->gone
;
193 nsignal
= cond
->to_unblock
= cond
->blocked
;
196 nsignal
= cond
->to_unblock
= 1;
200 LeaveCriticalSection(&cond
->monitor
);
203 ReleaseSemaphore(cond
->sem_queue
, nsignal
, NULL
);
206 static int impl_cond_do_wait(cnd_t
*cond
, mtx_t
*mtx
, const xtime
*xt
)
213 WaitForSingleObject(cond
->sem_gate
, INFINITE
);
215 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
219 w
= WaitForSingleObject(cond
->sem_queue
, xt
? impl_xtime2msec(xt
) : INFINITE
);
220 timeout
= (w
== WAIT_TIMEOUT
);
222 EnterCriticalSection(&cond
->monitor
);
223 if ((nleft
= cond
->to_unblock
) != 0) {
225 if (cond
->blocked
!= 0) {
231 if (--cond
->to_unblock
== 0) {
232 if (cond
->blocked
!= 0) {
233 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
236 else if ((ngone
= cond
->gone
) != 0) {
240 } else if (++cond
->gone
== INT_MAX
/2) {
241 WaitForSingleObject(cond
->sem_gate
, INFINITE
);
242 cond
->blocked
-= cond
->gone
;
243 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
246 LeaveCriticalSection(&cond
->monitor
);
250 WaitForSingleObject(cond
->sem_queue
, INFINITE
);
251 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
255 return timeout
? thrd_busy
: thrd_success
;
257 #endif // ifndef EMULATED_THREADS_USE_NATIVE_CV
259 static struct impl_tss_dtor_entry
{
262 } impl_tss_dtor_tbl
[EMULATED_THREADS_TSS_DTOR_SLOTNUM
];
264 static int impl_tss_dtor_register(tss_t key
, tss_dtor_t dtor
)
267 for (i
= 0; i
< EMULATED_THREADS_TSS_DTOR_SLOTNUM
; i
++) {
268 if (!impl_tss_dtor_tbl
[i
].dtor
)
271 if (i
== EMULATED_THREADS_TSS_DTOR_SLOTNUM
)
273 impl_tss_dtor_tbl
[i
].key
= key
;
274 impl_tss_dtor_tbl
[i
].dtor
= dtor
;
278 static void impl_tss_dtor_invoke()
281 for (i
= 0; i
< EMULATED_THREADS_TSS_DTOR_SLOTNUM
; i
++) {
282 if (impl_tss_dtor_tbl
[i
].dtor
) {
283 void* val
= tss_get(impl_tss_dtor_tbl
[i
].key
);
285 (impl_tss_dtor_tbl
[i
].dtor
)(val
);
291 /*--------------- 7.25.2 Initialization functions ---------------*/
294 call_once(once_flag
*flag
, void (*func
)(void))
296 assert(!flag
&& !func
);
297 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
299 struct impl_call_once_param param
;
301 InitOnceExecuteOnce(flag
, impl_call_once_callback
, (PVOID
)¶m
, NULL
);
304 if (InterlockedCompareExchange(&flag
->status
, 1, 0) == 0) {
306 InterlockedExchange(&flag
->status
, 2);
308 while (flag
->status
== 1) {
317 /*------------- 7.25.3 Condition variable functions -------------*/
320 cnd_broadcast(cnd_t
*cond
)
322 if (!cond
) return thrd_error
;
323 #ifdef EMULATED_THREADS_USE_NATIVE_CV
324 WakeAllConditionVariable(&cond
->condvar
);
326 impl_cond_do_signal(cond
, 1);
333 cnd_destroy(cnd_t
*cond
)
336 #ifdef EMULATED_THREADS_USE_NATIVE_CV
339 CloseHandle(cond
->sem_queue
);
340 CloseHandle(cond
->sem_gate
);
341 DeleteCriticalSection(&cond
->monitor
);
347 cnd_init(cnd_t
*cond
)
349 if (!cond
) return thrd_error
;
350 #ifdef EMULATED_THREADS_USE_NATIVE_CV
351 InitializeConditionVariable(&cond
->condvar
);
355 cond
->to_unblock
= 0;
356 cond
->sem_queue
= CreateSemaphore(NULL
, 0, LONG_MAX
, NULL
);
357 cond
->sem_gate
= CreateSemaphore(NULL
, 1, 1, NULL
);
358 InitializeCriticalSection(&cond
->monitor
);
365 cnd_signal(cnd_t
*cond
)
367 if (!cond
) return thrd_error
;
368 #ifdef EMULATED_THREADS_USE_NATIVE_CV
369 WakeConditionVariable(&cond
->condvar
);
371 impl_cond_do_signal(cond
, 0);
378 cnd_timedwait(cnd_t
*cond
, mtx_t
*mtx
, const xtime
*xt
)
380 if (!cond
|| !mtx
|| !xt
) return thrd_error
;
381 #ifdef EMULATED_THREADS_USE_NATIVE_CV
382 if (SleepConditionVariableCS(&cond
->condvar
, mtx
, impl_xtime2msec(xt
)))
384 return (GetLastError() == ERROR_TIMEOUT
) ? thrd_busy
: thrd_error
;
386 return impl_cond_do_wait(cond
, mtx
, xt
);
392 cnd_wait(cnd_t
*cond
, mtx_t
*mtx
)
394 if (!cond
|| !mtx
) return thrd_error
;
395 #ifdef EMULATED_THREADS_USE_NATIVE_CV
396 SleepConditionVariableCS(&cond
->condvar
, mtx
, INFINITE
);
398 impl_cond_do_wait(cond
, mtx
, NULL
);
404 /*-------------------- 7.25.4 Mutex functions --------------------*/
407 mtx_destroy(mtx_t
*mtx
)
410 DeleteCriticalSection(mtx
);
415 mtx_init(mtx_t
*mtx
, int type
)
417 if (!mtx
) return thrd_error
;
418 if (type
!= mtx_plain
&& type
!= mtx_timed
&& type
!= mtx_try
419 && type
!= (mtx_plain
|mtx_recursive
)
420 && type
!= (mtx_timed
|mtx_recursive
)
421 && type
!= (mtx_try
|mtx_recursive
))
423 InitializeCriticalSection(mtx
);
431 if (!mtx
) return thrd_error
;
432 EnterCriticalSection(mtx
);
438 mtx_timedlock(mtx_t
*mtx
, const xtime
*xt
)
441 if (!mtx
|| !xt
) return thrd_error
;
444 while (mtx_trylock(mtx
) != thrd_success
) {
456 mtx_trylock(mtx_t
*mtx
)
458 if (!mtx
) return thrd_error
;
459 return TryEnterCriticalSection(mtx
) ? thrd_success
: thrd_busy
;
464 mtx_unlock(mtx_t
*mtx
)
466 if (!mtx
) return thrd_error
;
467 LeaveCriticalSection(mtx
);
472 /*------------------- 7.25.5 Thread functions -------------------*/
475 thrd_create(thrd_t
*thr
, thrd_start_t func
, void *arg
)
477 struct impl_thrd_param
*pack
;
479 if (!thr
) return thrd_error
;
480 pack
= (struct impl_thrd_param
*)malloc(sizeof(struct impl_thrd_param
));
481 if (!pack
) return thrd_nomem
;
484 handle
= _beginthreadex(NULL
, 0, impl_thrd_routine
, pack
, 0, NULL
);
486 if (errno
== EAGAIN
|| errno
== EACCES
)
490 *thr
= (thrd_t
)handle
;
498 return GetCurrentThread();
503 thrd_detach(thrd_t thr
)
511 thrd_equal(thrd_t thr0
, thrd_t thr1
)
513 return (thr0
== thr1
);
520 impl_tss_dtor_invoke();
521 _endthreadex((unsigned)res
);
526 thrd_join(thrd_t thr
, int *res
)
529 w
= WaitForSingleObject(thr
, INFINITE
);
530 if (w
!= WAIT_OBJECT_0
)
533 if (!GetExitCodeThread(thr
, &code
)) {
545 thrd_sleep(const xtime
*xt
)
548 Sleep(impl_xtime2msec(xt
));
559 /*----------- 7.25.6 Thread-specific storage functions -----------*/
562 tss_create(tss_t
*key
, tss_dtor_t dtor
)
564 if (!key
) return thrd_error
;
567 if (impl_tss_dtor_register(*key
, dtor
)) {
572 return (*key
!= 0xFFFFFFFF) ? thrd_success
: thrd_error
;
577 tss_delete(tss_t key
)
586 return TlsGetValue(key
);
591 tss_set(tss_t key
, void *val
)
593 return TlsSetValue(key
, val
) ? thrd_success
: thrd_error
;
597 /*-------------------- 7.25.7 Time functions --------------------*/
600 xtime_get(xtime
*xt
, int base
)
603 if (base
== TIME_UTC
) {
604 xt
->sec
= time(NULL
);