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 */
80 #define HAVE_TIMESPEC_GET
83 /*---------------------------- macros ----------------------------*/
84 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
85 #define ONCE_FLAG_INIT INIT_ONCE_STATIC_INIT
87 #define ONCE_FLAG_INIT {0}
89 #define TSS_DTOR_ITERATIONS 1
91 // FIXME: temporary non-standard hack to ease transition
92 #define _MTX_INITIALIZER_NP {(PCRITICAL_SECTION_DEBUG)-1, -1, 0, 0, 0, 0}
94 /*---------------------------- types ----------------------------*/
95 typedef struct cnd_t
{
96 #ifdef EMULATED_THREADS_USE_NATIVE_CV
97 CONDITION_VARIABLE condvar
;
104 CRITICAL_SECTION monitor
;
108 typedef HANDLE thrd_t
;
112 typedef CRITICAL_SECTION mtx_t
;
114 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
115 typedef INIT_ONCE once_flag
;
117 typedef struct once_flag_t
{
118 volatile LONG status
;
123 static inline void * tss_get(tss_t key
);
124 static inline void thrd_yield(void);
125 static inline int mtx_trylock(mtx_t
*mtx
);
126 static inline int mtx_lock(mtx_t
*mtx
);
127 static inline int mtx_unlock(mtx_t
*mtx
);
130 Implementation limits:
131 - Conditionally emulation for "Initialization functions"
132 (see EMULATED_THREADS_USE_NATIVE_CALL_ONCE macro)
133 - Emulated `mtx_timelock()' with mtx_trylock() + *busy loop*
135 static void impl_tss_dtor_invoke(void); // forward decl.
137 struct impl_thrd_param
{
142 static unsigned __stdcall
impl_thrd_routine(void *p
)
144 struct impl_thrd_param pack
;
146 memcpy(&pack
, p
, sizeof(struct impl_thrd_param
));
148 code
= pack
.func(pack
.arg
);
149 impl_tss_dtor_invoke();
150 return (unsigned)code
;
153 static DWORD
impl_timespec2msec(const struct timespec
*ts
)
155 return (DWORD
)((ts
->tv_sec
* 1000U) + (ts
->tv_nsec
/ 1000000L));
158 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
159 struct impl_call_once_param
{ void (*func
)(void); };
160 static BOOL CALLBACK
impl_call_once_callback(PINIT_ONCE InitOnce
, PVOID Parameter
, PVOID
*Context
)
162 struct impl_call_once_param
*param
= (struct impl_call_once_param
*)Parameter
;
164 ((void)InitOnce
); ((void)Context
); // suppress warning
167 #endif // ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
169 #ifndef EMULATED_THREADS_USE_NATIVE_CV
172 The implementation of condition variable is ported from Boost.Interprocess
173 See http://www.boost.org/boost/interprocess/sync/windows/condition.hpp
175 static void impl_cond_do_signal(cnd_t
*cond
, int broadcast
)
179 EnterCriticalSection(&cond
->monitor
);
180 if (cond
->to_unblock
!= 0) {
181 if (cond
->blocked
== 0) {
182 LeaveCriticalSection(&cond
->monitor
);
186 cond
->to_unblock
+= nsignal
= cond
->blocked
;
193 } else if (cond
->blocked
> cond
->gone
) {
194 WaitForSingleObject(cond
->sem_gate
, INFINITE
);
195 if (cond
->gone
!= 0) {
196 cond
->blocked
-= cond
->gone
;
200 nsignal
= cond
->to_unblock
= cond
->blocked
;
203 nsignal
= cond
->to_unblock
= 1;
207 LeaveCriticalSection(&cond
->monitor
);
210 ReleaseSemaphore(cond
->sem_queue
, nsignal
, NULL
);
213 static int impl_cond_do_wait(cnd_t
*cond
, mtx_t
*mtx
, const struct timespec
*ts
)
220 WaitForSingleObject(cond
->sem_gate
, INFINITE
);
222 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
226 w
= WaitForSingleObject(cond
->sem_queue
, ts
? impl_timespec2msec(ts
) : INFINITE
);
227 timeout
= (w
== WAIT_TIMEOUT
);
229 EnterCriticalSection(&cond
->monitor
);
230 if ((nleft
= cond
->to_unblock
) != 0) {
232 if (cond
->blocked
!= 0) {
238 if (--cond
->to_unblock
== 0) {
239 if (cond
->blocked
!= 0) {
240 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
243 else if ((ngone
= cond
->gone
) != 0) {
247 } else if (++cond
->gone
== INT_MAX
/2) {
248 WaitForSingleObject(cond
->sem_gate
, INFINITE
);
249 cond
->blocked
-= cond
->gone
;
250 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
253 LeaveCriticalSection(&cond
->monitor
);
257 WaitForSingleObject(cond
->sem_queue
, INFINITE
);
258 ReleaseSemaphore(cond
->sem_gate
, 1, NULL
);
262 return timeout
? thrd_busy
: thrd_success
;
264 #endif // ifndef EMULATED_THREADS_USE_NATIVE_CV
266 static struct impl_tss_dtor_entry
{
269 } impl_tss_dtor_tbl
[EMULATED_THREADS_TSS_DTOR_SLOTNUM
];
271 static int impl_tss_dtor_register(tss_t key
, tss_dtor_t dtor
)
274 for (i
= 0; i
< EMULATED_THREADS_TSS_DTOR_SLOTNUM
; i
++) {
275 if (!impl_tss_dtor_tbl
[i
].dtor
)
278 if (i
== EMULATED_THREADS_TSS_DTOR_SLOTNUM
)
280 impl_tss_dtor_tbl
[i
].key
= key
;
281 impl_tss_dtor_tbl
[i
].dtor
= dtor
;
285 static void impl_tss_dtor_invoke()
288 for (i
= 0; i
< EMULATED_THREADS_TSS_DTOR_SLOTNUM
; i
++) {
289 if (impl_tss_dtor_tbl
[i
].dtor
) {
290 void* val
= tss_get(impl_tss_dtor_tbl
[i
].key
);
292 (impl_tss_dtor_tbl
[i
].dtor
)(val
);
298 /*--------------- 7.25.2 Initialization functions ---------------*/
301 call_once(once_flag
*flag
, void (*func
)(void))
303 assert(flag
&& func
);
304 #ifdef EMULATED_THREADS_USE_NATIVE_CALL_ONCE
306 struct impl_call_once_param param
;
308 InitOnceExecuteOnce(flag
, impl_call_once_callback
, (PVOID
)¶m
, NULL
);
311 if (InterlockedCompareExchange(&flag
->status
, 1, 0) == 0) {
313 InterlockedExchange(&flag
->status
, 2);
315 while (flag
->status
== 1) {
324 /*------------- 7.25.3 Condition variable functions -------------*/
327 cnd_broadcast(cnd_t
*cond
)
329 if (!cond
) return thrd_error
;
330 #ifdef EMULATED_THREADS_USE_NATIVE_CV
331 WakeAllConditionVariable(&cond
->condvar
);
333 impl_cond_do_signal(cond
, 1);
340 cnd_destroy(cnd_t
*cond
)
343 #ifdef EMULATED_THREADS_USE_NATIVE_CV
346 CloseHandle(cond
->sem_queue
);
347 CloseHandle(cond
->sem_gate
);
348 DeleteCriticalSection(&cond
->monitor
);
354 cnd_init(cnd_t
*cond
)
356 if (!cond
) return thrd_error
;
357 #ifdef EMULATED_THREADS_USE_NATIVE_CV
358 InitializeConditionVariable(&cond
->condvar
);
362 cond
->to_unblock
= 0;
363 cond
->sem_queue
= CreateSemaphore(NULL
, 0, LONG_MAX
, NULL
);
364 cond
->sem_gate
= CreateSemaphore(NULL
, 1, 1, NULL
);
365 InitializeCriticalSection(&cond
->monitor
);
372 cnd_signal(cnd_t
*cond
)
374 if (!cond
) return thrd_error
;
375 #ifdef EMULATED_THREADS_USE_NATIVE_CV
376 WakeConditionVariable(&cond
->condvar
);
378 impl_cond_do_signal(cond
, 0);
385 cnd_timedwait(cnd_t
*cond
, mtx_t
*mtx
, const struct timespec
*abs_time
)
387 if (!cond
|| !mtx
|| !abs_time
) return thrd_error
;
388 #ifdef EMULATED_THREADS_USE_NATIVE_CV
389 if (SleepConditionVariableCS(&cond
->condvar
, mtx
, impl_timespec2msec(abs_time
)))
391 return (GetLastError() == ERROR_TIMEOUT
) ? thrd_busy
: thrd_error
;
393 return impl_cond_do_wait(cond
, mtx
, abs_time
);
399 cnd_wait(cnd_t
*cond
, mtx_t
*mtx
)
401 if (!cond
|| !mtx
) return thrd_error
;
402 #ifdef EMULATED_THREADS_USE_NATIVE_CV
403 SleepConditionVariableCS(&cond
->condvar
, mtx
, INFINITE
);
405 impl_cond_do_wait(cond
, mtx
, NULL
);
411 /*-------------------- 7.25.4 Mutex functions --------------------*/
414 mtx_destroy(mtx_t
*mtx
)
417 DeleteCriticalSection(mtx
);
422 mtx_init(mtx_t
*mtx
, int type
)
424 if (!mtx
) return thrd_error
;
425 if (type
!= mtx_plain
&& type
!= mtx_timed
&& type
!= mtx_try
426 && type
!= (mtx_plain
|mtx_recursive
)
427 && type
!= (mtx_timed
|mtx_recursive
)
428 && type
!= (mtx_try
|mtx_recursive
))
430 InitializeCriticalSection(mtx
);
438 if (!mtx
) return thrd_error
;
439 EnterCriticalSection(mtx
);
445 mtx_timedlock(mtx_t
*mtx
, const struct timespec
*ts
)
448 if (!mtx
|| !ts
) return thrd_error
;
450 expire
+= ts
->tv_sec
;
451 while (mtx_trylock(mtx
) != thrd_success
) {
463 mtx_trylock(mtx_t
*mtx
)
465 if (!mtx
) return thrd_error
;
466 return TryEnterCriticalSection(mtx
) ? thrd_success
: thrd_busy
;
471 mtx_unlock(mtx_t
*mtx
)
473 if (!mtx
) return thrd_error
;
474 LeaveCriticalSection(mtx
);
479 /*------------------- 7.25.5 Thread functions -------------------*/
482 thrd_create(thrd_t
*thr
, thrd_start_t func
, void *arg
)
484 struct impl_thrd_param
*pack
;
486 if (!thr
) return thrd_error
;
487 pack
= (struct impl_thrd_param
*)malloc(sizeof(struct impl_thrd_param
));
488 if (!pack
) return thrd_nomem
;
491 handle
= _beginthreadex(NULL
, 0, impl_thrd_routine
, pack
, 0, NULL
);
493 if (errno
== EAGAIN
|| errno
== EACCES
)
497 *thr
= (thrd_t
)handle
;
506 HANDLE hCurrentThread
;
509 /* GetCurrentThread() returns a pseudo-handle, which we need
510 * to pass to DuplicateHandle(). Only the resulting handle can be used
511 * from other threads.
513 * Note that neither handle can be compared to the one by thread_create.
514 * Only the thread IDs - as returned by GetThreadId() and GetCurrentThreadId()
515 * can be compared directly.
517 * Other potential solutions would be:
518 * - define thrd_t as a thread Ids, but this would mean we'd need to OpenThread for many operations
519 * - use malloc'ed memory for thrd_t. This would imply using TLS for current thread.
521 * Neither is particularly nice.
523 * Life would be much easier if C11 threads had different abstractions for
524 * threads and thread IDs, just like C++11 threads does...
527 bRet
= DuplicateHandle(GetCurrentProcess(), // source process (pseudo) handle
528 GetCurrentThread(), // source (pseudo) handle
529 GetCurrentProcess(), // target process
530 &hCurrentThread
, // target handle
533 DUPLICATE_SAME_ACCESS
);
536 hCurrentThread
= GetCurrentThread();
538 return hCurrentThread
;
544 thrd_detach(thrd_t thr
)
552 thrd_equal(thrd_t thr0
, thrd_t thr1
)
554 return GetThreadId(thr0
) == GetThreadId(thr1
);
561 impl_tss_dtor_invoke();
562 _endthreadex((unsigned)res
);
567 thrd_join(thrd_t thr
, int *res
)
570 w
= WaitForSingleObject(thr
, INFINITE
);
571 if (w
!= WAIT_OBJECT_0
)
574 if (!GetExitCodeThread(thr
, &code
)) {
586 thrd_sleep(const struct timespec
*time_point
, struct timespec
*remaining
)
589 assert(!remaining
); /* not implemented */
590 Sleep(impl_timespec2msec(time_point
));
601 /*----------- 7.25.6 Thread-specific storage functions -----------*/
604 tss_create(tss_t
*key
, tss_dtor_t dtor
)
606 if (!key
) return thrd_error
;
609 if (impl_tss_dtor_register(*key
, dtor
)) {
614 return (*key
!= 0xFFFFFFFF) ? thrd_success
: thrd_error
;
619 tss_delete(tss_t key
)
628 return TlsGetValue(key
);
633 tss_set(tss_t key
, void *val
)
635 return TlsSetValue(key
, val
) ? thrd_success
: thrd_error
;
639 /*-------------------- 7.25.7 Time functions --------------------*/
641 #ifndef HAVE_TIMESPEC_GET
643 timespec_get(struct timespec
*ts
, int base
)
646 if (base
== TIME_UTC
) {
647 ts
->tv_sec
= time(NULL
);