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.
34 #include <process.h> // MSVCRT
40 EMULATED_THREADS_USE_NATIVE_CALL_ONCE
41 Use native WindowsAPI one-time initialization function.
42 (requires WinVista or later)
43 Otherwise emulate by mtx_trylock() + *busy loop* for WinXP.
45 EMULATED_THREADS_USE_NATIVE_CV
46 Use native WindowsAPI condition variable object.
47 (requires WinVista or later)
48 Otherwise use emulated implementation for WinXP.
50 EMULATED_THREADS_TSS_DTOR_SLOTNUM
51 Max registerable TSS dtor number.
54 // XXX: Retain XP compatability
56 #if _WIN32_WINNT >= 0x0600
57 // Prefer native WindowsAPI on newer environment.
58 #if !defined(__MINGW32__)
59 #define EMULATED_THREADS_USE_NATIVE_CALL_ONCE
61 #define EMULATED_THREADS_USE_NATIVE_CV
64 #define EMULATED_THREADS_TSS_DTOR_SLOTNUM 64 // see TLS_MINIMUM_AVAILABLE
69 // check configuration
70 #if defined(EMULATED_THREADS_USE_NATIVE_CALL_ONCE) && (_WIN32_WINNT < 0x0600)
71 #error EMULATED_THREADS_USE_NATIVE_CALL_ONCE requires _WIN32_WINNT>=0x0600
74 #if defined(EMULATED_THREADS_USE_NATIVE_CV) && (_WIN32_WINNT < 0x0600)
75 #error EMULATED_THREADS_USE_NATIVE_CV requires _WIN32_WINNT>=0x0600
78 /* Visual Studio 2015 and later */
90 /*---------------------------- macros ----------------------------*/
91 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
92 #define ONCE_FLAG_INIT INIT_ONCE_STATIC_INIT
94 #define ONCE_FLAG_INIT {0}
96 #define TSS_DTOR_ITERATIONS 1
98 // FIXME: temporary non-standard hack to ease transition
99 #define _MTX_INITIALIZER_NP {(PCRITICAL_SECTION_DEBUG)-1, -1, 0, 0, 0, 0}
101 /*---------------------------- types ----------------------------*/
102 typedef struct cnd_t
{
103 #ifdef EMULATED_THREADS_USE_NATIVE_CV
104 CONDITION_VARIABLE condvar
;
111 CRITICAL_SECTION monitor
;
115 typedef HANDLE thrd_t
;
119 typedef CRITICAL_SECTION mtx_t
;
121 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
122 typedef INIT_ONCE once_flag
;
124 typedef struct once_flag_t
{
125 volatile LONG status
;
130 static inline void * tss_get(tss_t key
);
131 static inline void thrd_yield(void);
132 static inline int mtx_trylock(mtx_t
*mtx
);
133 static inline int mtx_lock(mtx_t
*mtx
);
134 static inline int mtx_unlock(mtx_t
*mtx
);
137 Implementation limits:
138 - Conditionally emulation for "Initialization functions"
139 (see EMULATED_THREADS_USE_NATIVE_CALL_ONCE macro)
140 - Emulated `mtx_timelock()' with mtx_trylock() + *busy loop*
142 static void impl_tss_dtor_invoke(void); // forward decl.
144 struct impl_thrd_param
{
149 static unsigned __stdcall
impl_thrd_routine(void *p
)
151 struct impl_thrd_param pack
;
153 memcpy(&pack
, p
, sizeof(struct impl_thrd_param
));
155 code
= pack
.func(pack
.arg
);
156 impl_tss_dtor_invoke();
157 return (unsigned)code
;
160 static DWORD
impl_timespec2msec(const struct timespec
*ts
)
162 return (DWORD
)((ts
->tv_sec
* 1000U) + (ts
->tv_nsec
/ 1000000L));
165 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
166 struct impl_call_once_param
{ void (*func
)(void); };
167 static BOOL CALLBACK
impl_call_once_callback(PINIT_ONCE InitOnce
, PVOID Parameter
, PVOID
*Context
)
169 struct impl_call_once_param
*param
= (struct impl_call_once_param
*)Parameter
;
171 ((void)InitOnce
); ((void)Context
); // suppress warning
174 #endif // ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
176 #ifndef EMULATED_THREADS_USE_NATIVE_CV
179 The implementation of condition variable is ported from Boost.Interprocess
180 See http://www.boost.org/boost/interprocess/sync/windows/condition.hpp
182 static void impl_cond_do_signal(cnd_t
*cond
, int broadcast
)
186 EnterCriticalSection(&cond
->monitor
);
187 if (cond
->to_unblock
!= 0) {
188 if (cond
->blocked
== 0) {
189 LeaveCriticalSection(&cond
->monitor
);
193 cond
->to_unblock
+= nsignal
= cond
->blocked
;
200 } else if (cond
->blocked
> cond
->gone
) {
201 WaitForSingleObject(cond
->sem_gate
, INFINITE
);
202 if (cond
->gone
!= 0) {
203 cond
->blocked
-= cond
->gone
;
207 nsignal
= cond
->to_unblock
= cond
->blocked
;
210 nsignal
= cond
->to_unblock
= 1;
214 LeaveCriticalSection(&cond
->monitor
);
217 ReleaseSemaphore(cond
->sem_queue
, nsignal
, NULL
);
220 static int impl_cond_do_wait(cnd_t
*cond
, mtx_t
*mtx
, const struct timespec
*ts
)
227 WaitForSingleObject(cond
->sem_gate
, INFINITE
);
229 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
233 w
= WaitForSingleObject(cond
->sem_queue
, ts
? impl_timespec2msec(ts
) : INFINITE
);
234 timeout
= (w
== WAIT_TIMEOUT
);
236 EnterCriticalSection(&cond
->monitor
);
237 if ((nleft
= cond
->to_unblock
) != 0) {
239 if (cond
->blocked
!= 0) {
245 if (--cond
->to_unblock
== 0) {
246 if (cond
->blocked
!= 0) {
247 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
250 else if ((ngone
= cond
->gone
) != 0) {
254 } else if (++cond
->gone
== INT_MAX
/2) {
255 WaitForSingleObject(cond
->sem_gate
, INFINITE
);
256 cond
->blocked
-= cond
->gone
;
257 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
260 LeaveCriticalSection(&cond
->monitor
);
264 WaitForSingleObject(cond
->sem_queue
, INFINITE
);
265 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
269 return timeout
? thrd_busy
: thrd_success
;
271 #endif // ifndef EMULATED_THREADS_USE_NATIVE_CV
273 static struct impl_tss_dtor_entry
{
276 } impl_tss_dtor_tbl
[EMULATED_THREADS_TSS_DTOR_SLOTNUM
];
278 static int impl_tss_dtor_register(tss_t key
, tss_dtor_t dtor
)
281 for (i
= 0; i
< EMULATED_THREADS_TSS_DTOR_SLOTNUM
; i
++) {
282 if (!impl_tss_dtor_tbl
[i
].dtor
)
285 if (i
== EMULATED_THREADS_TSS_DTOR_SLOTNUM
)
287 impl_tss_dtor_tbl
[i
].key
= key
;
288 impl_tss_dtor_tbl
[i
].dtor
= dtor
;
292 static void impl_tss_dtor_invoke()
295 for (i
= 0; i
< EMULATED_THREADS_TSS_DTOR_SLOTNUM
; i
++) {
296 if (impl_tss_dtor_tbl
[i
].dtor
) {
297 void* val
= tss_get(impl_tss_dtor_tbl
[i
].key
);
299 (impl_tss_dtor_tbl
[i
].dtor
)(val
);
305 /*--------------- 7.25.2 Initialization functions ---------------*/
308 call_once(once_flag
*flag
, void (*func
)(void))
310 assert(flag
&& func
);
311 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
313 struct impl_call_once_param param
;
315 InitOnceExecuteOnce(flag
, impl_call_once_callback
, (PVOID
)¶m
, NULL
);
318 if (InterlockedCompareExchange(&flag
->status
, 1, 0) == 0) {
320 InterlockedExchange(&flag
->status
, 2);
322 while (flag
->status
== 1) {
331 /*------------- 7.25.3 Condition variable functions -------------*/
334 cnd_broadcast(cnd_t
*cond
)
336 if (!cond
) return thrd_error
;
337 #ifdef EMULATED_THREADS_USE_NATIVE_CV
338 WakeAllConditionVariable(&cond
->condvar
);
340 impl_cond_do_signal(cond
, 1);
347 cnd_destroy(cnd_t
*cond
)
350 #ifdef EMULATED_THREADS_USE_NATIVE_CV
353 CloseHandle(cond
->sem_queue
);
354 CloseHandle(cond
->sem_gate
);
355 DeleteCriticalSection(&cond
->monitor
);
361 cnd_init(cnd_t
*cond
)
363 if (!cond
) return thrd_error
;
364 #ifdef EMULATED_THREADS_USE_NATIVE_CV
365 InitializeConditionVariable(&cond
->condvar
);
369 cond
->to_unblock
= 0;
370 cond
->sem_queue
= CreateSemaphore(NULL
, 0, LONG_MAX
, NULL
);
371 cond
->sem_gate
= CreateSemaphore(NULL
, 1, 1, NULL
);
372 InitializeCriticalSection(&cond
->monitor
);
379 cnd_signal(cnd_t
*cond
)
381 if (!cond
) return thrd_error
;
382 #ifdef EMULATED_THREADS_USE_NATIVE_CV
383 WakeConditionVariable(&cond
->condvar
);
385 impl_cond_do_signal(cond
, 0);
392 cnd_timedwait(cnd_t
*cond
, mtx_t
*mtx
, const struct timespec
*abs_time
)
394 if (!cond
|| !mtx
|| !abs_time
) return thrd_error
;
395 #ifdef EMULATED_THREADS_USE_NATIVE_CV
396 if (SleepConditionVariableCS(&cond
->condvar
, mtx
, impl_timespec2msec(abs_time
)))
398 return (GetLastError() == ERROR_TIMEOUT
) ? thrd_busy
: thrd_error
;
400 return impl_cond_do_wait(cond
, mtx
, abs_time
);
406 cnd_wait(cnd_t
*cond
, mtx_t
*mtx
)
408 if (!cond
|| !mtx
) return thrd_error
;
409 #ifdef EMULATED_THREADS_USE_NATIVE_CV
410 SleepConditionVariableCS(&cond
->condvar
, mtx
, INFINITE
);
412 impl_cond_do_wait(cond
, mtx
, NULL
);
418 /*-------------------- 7.25.4 Mutex functions --------------------*/
421 mtx_destroy(mtx_t
*mtx
)
424 DeleteCriticalSection(mtx
);
429 mtx_init(mtx_t
*mtx
, int type
)
431 if (!mtx
) return thrd_error
;
432 if (type
!= mtx_plain
&& type
!= mtx_timed
&& type
!= mtx_try
433 && type
!= (mtx_plain
|mtx_recursive
)
434 && type
!= (mtx_timed
|mtx_recursive
)
435 && type
!= (mtx_try
|mtx_recursive
))
437 InitializeCriticalSection(mtx
);
445 if (!mtx
) return thrd_error
;
446 EnterCriticalSection(mtx
);
452 mtx_timedlock(mtx_t
*mtx
, const struct timespec
*ts
)
455 if (!mtx
|| !ts
) return thrd_error
;
457 expire
+= ts
->tv_sec
;
458 while (mtx_trylock(mtx
) != thrd_success
) {
470 mtx_trylock(mtx_t
*mtx
)
472 if (!mtx
) return thrd_error
;
473 return TryEnterCriticalSection(mtx
) ? thrd_success
: thrd_busy
;
478 mtx_unlock(mtx_t
*mtx
)
480 if (!mtx
) return thrd_error
;
481 LeaveCriticalSection(mtx
);
486 /*------------------- 7.25.5 Thread functions -------------------*/
489 thrd_create(thrd_t
*thr
, thrd_start_t func
, void *arg
)
491 struct impl_thrd_param
*pack
;
493 if (!thr
) return thrd_error
;
494 pack
= (struct impl_thrd_param
*)malloc(sizeof(struct impl_thrd_param
));
495 if (!pack
) return thrd_nomem
;
498 handle
= _beginthreadex(NULL
, 0, impl_thrd_routine
, pack
, 0, NULL
);
500 if (errno
== EAGAIN
|| errno
== EACCES
)
504 *thr
= (thrd_t
)handle
;
513 HANDLE hCurrentThread
;
516 /* GetCurrentThread() returns a pseudo-handle, which we need
517 * to pass to DuplicateHandle(). Only the resulting handle can be used
518 * from other threads.
520 * Note that neither handle can be compared to the one by thread_create.
521 * Only the thread IDs - as returned by GetThreadId() and GetCurrentThreadId()
522 * can be compared directly.
524 * Other potential solutions would be:
525 * - define thrd_t as a thread Ids, but this would mean we'd need to OpenThread for many operations
526 * - use malloc'ed memory for thrd_t. This would imply using TLS for current thread.
528 * Neither is particularly nice.
530 * Life would be much easier if C11 threads had different abstractions for
531 * threads and thread IDs, just like C++11 threads does...
534 bRet
= DuplicateHandle(GetCurrentProcess(), // source process (pseudo) handle
535 GetCurrentThread(), // source (pseudo) handle
536 GetCurrentProcess(), // target process
537 &hCurrentThread
, // target handle
540 DUPLICATE_SAME_ACCESS
);
543 hCurrentThread
= GetCurrentThread();
545 return hCurrentThread
;
551 thrd_detach(thrd_t thr
)
559 thrd_equal(thrd_t thr0
, thrd_t thr1
)
561 return GetThreadId(thr0
) == GetThreadId(thr1
);
568 impl_tss_dtor_invoke();
569 _endthreadex((unsigned)res
);
574 thrd_join(thrd_t thr
, int *res
)
577 w
= WaitForSingleObject(thr
, INFINITE
);
578 if (w
!= WAIT_OBJECT_0
)
581 if (!GetExitCodeThread(thr
, &code
)) {
593 thrd_sleep(const struct timespec
*time_point
, struct timespec
*remaining
)
596 assert(!remaining
); /* not implemented */
597 Sleep(impl_timespec2msec(time_point
));
608 /*----------- 7.25.6 Thread-specific storage functions -----------*/
611 tss_create(tss_t
*key
, tss_dtor_t dtor
)
613 if (!key
) return thrd_error
;
616 if (impl_tss_dtor_register(*key
, dtor
)) {
621 return (*key
!= 0xFFFFFFFF) ? thrd_success
: thrd_error
;
626 tss_delete(tss_t key
)
635 return TlsGetValue(key
);
640 tss_set(tss_t key
, void *val
)
642 return TlsSetValue(key
, val
) ? thrd_success
: thrd_error
;
646 /*-------------------- 7.25.7 Time functions --------------------*/
648 #ifndef HAVE_TIMESPEC
650 timespec_get(struct timespec
*ts
, int base
)
653 if (base
== TIME_UTC
) {
654 ts
->tv_sec
= time(NULL
);