From ed3a1e70f207ec3d6bb546dd88fde5eaf5680071 Mon Sep 17 00:00:00 2001 From: Gust Date: Tue, 27 Feb 2024 20:13:54 +0800 Subject: [PATCH] update thread source, optimize java threadlock function --- minijvm/c/jvm/jdwp.c | 2 +- minijvm/c/jvm/jni_std.c | 1 + minijvm/c/jvm/jvm_util.c | 30 +- minijvm/c/main.c | 14 +- minijvm/c/utils/tinycthread.c | 1043 ++++++++++++++++++++++----------- minijvm/c/utils/tinycthread.h | 147 +++-- 6 files changed, 829 insertions(+), 408 deletions(-) diff --git a/minijvm/c/jvm/jdwp.c b/minijvm/c/jvm/jdwp.c index 243155e40..1cefa49e6 100644 --- a/minijvm/c/jvm/jdwp.c +++ b/minijvm/c/jvm/jdwp.c @@ -127,7 +127,7 @@ s32 jdwp_start_server(MiniJVM *jvm) { jdwpserver->event_sets = pairlist_create(32); jdwpserver->runtime_jdwp = runtime_create(jvm); jdwpserver->runtime_jdwp->thrd_info->type = THREAD_TYPE_JDWP; - mtx_init(&jdwpserver->event_sets_lock, mtx_recursive); + mtx_init(&jdwpserver->event_sets_lock, mtx_recursive | mtx_timed); jvm->jdwpserver = jdwpserver; thrd_create(&jdwpserver->pt_listener, jdwp_thread_listener, jdwpserver); diff --git a/minijvm/c/jvm/jni_std.c b/minijvm/c/jvm/jni_std.c index 5971d6d68..c7808bd72 100644 --- a/minijvm/c/jvm/jni_std.c +++ b/minijvm/c/jvm/jni_std.c @@ -974,6 +974,7 @@ s32 java_lang_System_loadLibrary0(Runtime *runtime, JClass *clazz) { f = (jni_fun) fp; f(runtime->jvm); } + break; } #else diff --git a/minijvm/c/jvm/jvm_util.c b/minijvm/c/jvm/jvm_util.c index a05e3a6de..945c2b72d 100644 --- a/minijvm/c/jvm/jvm_util.c +++ b/minijvm/c/jvm/jvm_util.c @@ -325,7 +325,7 @@ void thread_stop_all(MiniJVM *jvm) { void thread_lock_init(ThreadLock *lock) { if (lock) { cnd_init(&lock->thread_cond); - mtx_init(&lock->mutex_lock, mtx_recursive); + mtx_init(&lock->mutex_lock, mtx_recursive | mtx_timed); } } @@ -996,20 +996,28 @@ s32 jthread_lock(MemoryBlock *mb, Runtime *runtime) { //可能会重入,同一 jthreadlock_create(runtime, mb); } ThreadLock *jtl = mb->thread_lock; + s32 i = 0; +#if _JVM_DEBUG_LOG_LEVEL > 5 + s64 waitTime = currentTimeMillis(); +#endif + struct timespec t; + t.tv_nsec = 5 * NANO_2_MILLS_SCALE; + t.tv_sec = 0; //can pause when lock - while (mtx_trylock(&jtl->mutex_lock) != thrd_success) { + while (mtx_timedlock(&jtl->mutex_lock, &t) != thrd_success) { check_suspend_and_pause(runtime); if (runtime->thrd_info->type == THREAD_TYPE_JDWP) { break; } - //jthread_yield(runtime); - jthread_waitTime(mb, runtime, 20); + jthread_yield(runtime); + i++; } - #if _JVM_DEBUG_LOG_LEVEL > 5 - invoke_deepth(runtime); - jvm_printf(" lock: %llx lock holder: %s \n", (s64) (intptr_t) (runtime->thrd_info->jthread), - utf8_cstr(mb->clazz->name)); + if (i > 0) { + waitTime = currentTimeMillis() - waitTime; + invoke_deepth(runtime); + jvm_printf(" lock holder: %s , lock count: %d waitTime: %lld \n", utf8_cstr(mb->clazz->name), i, waitTime); + } #endif return 0; } @@ -1851,9 +1859,9 @@ s64 nanoTime() { s64 threadSleep(s64 ms) { //wait time struct timespec req; - clock_gettime(CLOCK_REALTIME, &req); - req.tv_sec += ms / MILL_2_SEC_SCALE; - req.tv_nsec += (ms % MILL_2_SEC_SCALE) * NANO_2_MILLS_SCALE; + //clock_gettime(CLOCK_REALTIME, &req); + req.tv_sec = ms / MILL_2_SEC_SCALE; + req.tv_nsec = (ms % MILL_2_SEC_SCALE) * NANO_2_MILLS_SCALE; //if notify or notifyall ,the thread is active again, rem record remain wait time struct timespec rem; rem.tv_sec = 0; diff --git a/minijvm/c/main.c b/minijvm/c/main.c index ccfc3920e..f581de202 100644 --- a/minijvm/c/main.c +++ b/minijvm/c/main.c @@ -88,10 +88,10 @@ int main(int argc, char **argv) { //compiler test // utf8_append(cp, startup_dir); // utf8_append_c(cp, "../libex/janino.jar"); - utf8_append_c(cp, PATHSEPARATOR); +// utf8_append_c(cp, PATHSEPARATOR); // utf8_append(cp, startup_dir); // utf8_append_c(cp, "../libex/commons-compiler.jar"); - utf8_append_c(cp, PATHSEPARATOR); +// utf8_append_c(cp, PATHSEPARATOR); // classpath = (c8 *) utf8_cstr(cp); // main_name = "org.codehaus.janino.Compiler"; // arraylist_push_back(java_para,"../res/BpDeepTest.java"); @@ -99,12 +99,12 @@ int main(int argc, char **argv) { //test awtk // utf8_append(cp, startup_dir); // utf8_append_c(cp, "../libex/awtk_gui.jar"); - utf8_append_c(cp, PATHSEPARATOR); +// utf8_append_c(cp, PATHSEPARATOR); // utf8_append(cp, startup_dir); // utf8_append_c(cp, "../libex/awtk_demos.jar"); - utf8_append_c(cp, PATHSEPARATOR); +// utf8_append_c(cp, PATHSEPARATOR); // utf8_append_c(cp, "./"); - utf8_append_c(cp, PATHSEPARATOR); +// utf8_append_c(cp, PATHSEPARATOR); // classpath = (c8 *) utf8_cstr(cp); // main_name = "DemoBasic"; // main_name = "DemoButton"; @@ -112,9 +112,9 @@ int main(int argc, char **argv) { //test luaj // utf8_append(cp, startup_dir); // utf8_append_c(cp, "../libex/luncher.jar"); - utf8_append_c(cp, PATHSEPARATOR); +// utf8_append_c(cp, PATHSEPARATOR); // utf8_append_c(cp, "./"); - utf8_append_c(cp, PATHSEPARATOR); +// utf8_append_c(cp, PATHSEPARATOR); // classpath = (c8 *) utf8_cstr(cp); // main_name = "org.luaj.vm2.lib.jme.TestLuaJ"; diff --git a/minijvm/c/utils/tinycthread.c b/minijvm/c/utils/tinycthread.c index 27233ea64..195e413fe 100644 --- a/minijvm/c/utils/tinycthread.c +++ b/minijvm/c/utils/tinycthread.c @@ -1,5 +1,6 @@ /* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*- Copyright (c) 2012 Marcus Geelnard +Copyright (c) 2013-2016 Evan Nemerson This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -21,108 +22,261 @@ freely, subject to the following restrictions: distribution. */ -/* 2013-01-06 Camilla Löwy - * - * Added casts from time_t to DWORD to avoid warnings on VC++. - * Fixed time retrieval on POSIX systems. - */ - #include "tinycthread.h" #include /* Platform specific includes */ #if defined(_TTHREAD_POSIX_) -#include -#include -#include -#include -#include + #include + #include + #include + #include + #include #elif defined(_TTHREAD_WIN32_) - -#include -#include - + #include + #include #endif /* Standard, good-to-have defines */ #ifndef NULL -#define NULL (void*)0 + #define NULL (void*)0 #endif #ifndef TRUE -#define TRUE 1 + #define TRUE 1 #endif #ifndef FALSE -#define FALSE 0 + #define FALSE 0 #endif -int mtx_init(mtx_t *mtx, int type) { +#ifdef __cplusplus +extern "C" { +#endif + + +int mtx_init(mtx_t *mtx, int type) +{ #if defined(_TTHREAD_WIN32_) - mtx->mAlreadyLocked = FALSE; - mtx->mRecursive = type & mtx_recursive; - InitializeCriticalSection(&mtx->mHandle); - return thrd_success; -#else - int ret; - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); - if (type & mtx_recursive) + mtx->mAlreadyLocked = FALSE; + mtx->mRecursive = type & mtx_recursive; + mtx->mTimed = type & mtx_timed; + if (!mtx->mTimed) + { + InitializeCriticalSection(&(mtx->mHandle.cs)); + } + else + { + mtx->mHandle.mut = CreateMutex(NULL, FALSE, NULL); + if (mtx->mHandle.mut == NULL) { - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + return thrd_error; } - ret = pthread_mutex_init(mtx, &attr); - pthread_mutexattr_destroy(&attr); - return ret == 0 ? thrd_success : thrd_error; + } + return thrd_success; +#else + int ret; + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + if (type & mtx_recursive) + { + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + } + ret = pthread_mutex_init(mtx, &attr); + pthread_mutexattr_destroy(&attr); + return ret == 0 ? thrd_success : thrd_error; #endif } -void mtx_destroy(mtx_t *mtx) { +void mtx_destroy(mtx_t *mtx) +{ #if defined(_TTHREAD_WIN32_) - DeleteCriticalSection(&mtx->mHandle); + if (!mtx->mTimed) + { + DeleteCriticalSection(&(mtx->mHandle.cs)); + } + else + { + CloseHandle(mtx->mHandle.mut); + } #else - pthread_mutex_destroy(mtx); + pthread_mutex_destroy(mtx); #endif } -int mtx_lock(mtx_t *mtx) { +int mtx_lock(mtx_t *mtx) +{ #if defined(_TTHREAD_WIN32_) - EnterCriticalSection(&mtx->mHandle); - if (!mtx->mRecursive) { - while (mtx->mAlreadyLocked) Sleep(1000); /* Simulate deadlock... */ - mtx->mAlreadyLocked = TRUE; + if (!mtx->mTimed) + { + EnterCriticalSection(&(mtx->mHandle.cs)); + } + else + { + switch (WaitForSingleObject(mtx->mHandle.mut, INFINITE)) + { + case WAIT_OBJECT_0: + break; + case WAIT_ABANDONED: + default: + return thrd_error; } - return thrd_success; + } + + if (!mtx->mRecursive) + { + while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */ + mtx->mAlreadyLocked = TRUE; + } + return thrd_success; #else - return pthread_mutex_lock(mtx) == 0 ? thrd_success : thrd_error; + return pthread_mutex_lock(mtx) == 0 ? thrd_success : thrd_error; #endif } -int mtx_timedlock(mtx_t *mtx, const struct timespec *ts) { - /* FIXME! */ - (void) mtx; - (void) ts; +int mtx_timedlock(mtx_t *mtx, const struct timespec *ts) +{ +#if defined(_TTHREAD_WIN32_) + struct timespec current_ts; + DWORD timeoutMs; + + if (!mtx->mTimed) + { return thrd_error; + } + + timespec_get(¤t_ts, TIME_UTC); + + if ((current_ts.tv_sec > ts->tv_sec) || ((current_ts.tv_sec == ts->tv_sec) && (current_ts.tv_nsec >= ts->tv_nsec))) + { + timeoutMs = 0; + } + else + { + timeoutMs = (DWORD)(ts->tv_sec - current_ts.tv_sec) * 1000; + timeoutMs += (ts->tv_nsec - current_ts.tv_nsec) / 1000000; + timeoutMs += 1; + } + + /* TODO: the timeout for WaitForSingleObject doesn't include time + while the computer is asleep. */ + switch (WaitForSingleObject(mtx->mHandle.mut, timeoutMs)) + { + case WAIT_OBJECT_0: + break; + case WAIT_TIMEOUT: + return thrd_timedout; + case WAIT_ABANDONED: + default: + return thrd_error; + } + + if (!mtx->mRecursive) + { + while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */ + mtx->mAlreadyLocked = TRUE; + } + + return thrd_success; +#elif defined(_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS >= 200112L) && defined(_POSIX_THREADS) && (_POSIX_THREADS >= 200112L) + switch (pthread_mutex_timedlock(mtx, ts)) { + case 0: + return thrd_success; + case ETIMEDOUT: + return thrd_timedout; + default: + return thrd_error; + } +#else + int rc; + struct timespec cur, dur; + + /* Try to acquire the lock and, if we fail, sleep for 5ms. */ + while ((rc = pthread_mutex_trylock (mtx)) == EBUSY) { + timespec_get(&cur, TIME_UTC); + + if ((cur.tv_sec > ts->tv_sec) || ((cur.tv_sec == ts->tv_sec) && (cur.tv_nsec >= ts->tv_nsec))) + { + break; + } + + dur.tv_sec = ts->tv_sec - cur.tv_sec; + dur.tv_nsec = ts->tv_nsec - cur.tv_nsec; + if (dur.tv_nsec < 0) + { + dur.tv_sec--; + dur.tv_nsec += 1000000000; + } + + if ((dur.tv_sec != 0) || (dur.tv_nsec > 5000000)) + { + dur.tv_sec = 0; + dur.tv_nsec = 5000000; + } + + nanosleep(&dur, NULL); + } + + switch (rc) { + case 0: + return thrd_success; + case ETIMEDOUT: + case EBUSY: + return thrd_timedout; + default: + return thrd_error; + } +#endif } -int mtx_trylock(mtx_t *mtx) { +int mtx_trylock(mtx_t *mtx) +{ #if defined(_TTHREAD_WIN32_) - int ret = TryEnterCriticalSection(&mtx->mHandle) ? thrd_success : thrd_busy; - if ((!mtx->mRecursive) && (ret == thrd_success) && mtx->mAlreadyLocked) { - LeaveCriticalSection(&mtx->mHandle); - ret = thrd_busy; + int ret; + + if (!mtx->mTimed) + { + ret = TryEnterCriticalSection(&(mtx->mHandle.cs)) ? thrd_success : thrd_busy; + } + else + { + ret = (WaitForSingleObject(mtx->mHandle.mut, 0) == WAIT_OBJECT_0) ? thrd_success : thrd_busy; + } + + if ((!mtx->mRecursive) && (ret == thrd_success)) + { + if (mtx->mAlreadyLocked) + { + LeaveCriticalSection(&(mtx->mHandle.cs)); + ret = thrd_busy; } - return ret; + else + { + mtx->mAlreadyLocked = TRUE; + } + } + return ret; #else - return (pthread_mutex_trylock(mtx) == 0) ? thrd_success : thrd_busy; + return (pthread_mutex_trylock(mtx) == 0) ? thrd_success : thrd_busy; #endif } -int mtx_unlock(mtx_t *mtx) { +int mtx_unlock(mtx_t *mtx) +{ #if defined(_TTHREAD_WIN32_) - mtx->mAlreadyLocked = FALSE; - LeaveCriticalSection(&mtx->mHandle); - return thrd_success; + mtx->mAlreadyLocked = FALSE; + if (!mtx->mTimed) + { + LeaveCriticalSection(&(mtx->mHandle.cs)); + } + else + { + if (!ReleaseMutex(mtx->mHandle.mut)) + { + return thrd_error; + } + } + return thrd_success; #else - return pthread_mutex_unlock(mtx) == 0 ? thrd_success : thrd_error;; + return pthread_mutex_unlock(mtx) == 0 ? thrd_success : thrd_error;; #endif } @@ -131,420 +285,647 @@ int mtx_unlock(mtx_t *mtx) { #define _CONDITION_EVENT_ALL 1 #endif -int cnd_init(cnd_t *cond) { +int cnd_init(cnd_t *cond) +{ #if defined(_TTHREAD_WIN32_) - cond->mWaitersCount = 0; + cond->mWaitersCount = 0; - /* Init critical section */ - InitializeCriticalSection(&cond->mWaitersCountLock); + /* Init critical section */ + InitializeCriticalSection(&cond->mWaitersCountLock); - /* Init events */ - cond->mEvents[_CONDITION_EVENT_ONE] = CreateEvent(NULL, FALSE, FALSE, NULL); - if (cond->mEvents[_CONDITION_EVENT_ONE] == NULL) { - cond->mEvents[_CONDITION_EVENT_ALL] = NULL; - return thrd_error; - } - cond->mEvents[_CONDITION_EVENT_ALL] = CreateEvent(NULL, TRUE, FALSE, NULL); - if (cond->mEvents[_CONDITION_EVENT_ALL] == NULL) { - CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]); - cond->mEvents[_CONDITION_EVENT_ONE] = NULL; - return thrd_error; - } + /* Init events */ + cond->mEvents[_CONDITION_EVENT_ONE] = CreateEvent(NULL, FALSE, FALSE, NULL); + if (cond->mEvents[_CONDITION_EVENT_ONE] == NULL) + { + cond->mEvents[_CONDITION_EVENT_ALL] = NULL; + return thrd_error; + } + cond->mEvents[_CONDITION_EVENT_ALL] = CreateEvent(NULL, TRUE, FALSE, NULL); + if (cond->mEvents[_CONDITION_EVENT_ALL] == NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]); + cond->mEvents[_CONDITION_EVENT_ONE] = NULL; + return thrd_error; + } - return thrd_success; + return thrd_success; #else - return pthread_cond_init(cond, NULL) == 0 ? thrd_success : thrd_error; + return pthread_cond_init(cond, NULL) == 0 ? thrd_success : thrd_error; #endif } -void cnd_destroy(cnd_t *cond) { +void cnd_destroy(cnd_t *cond) +{ #if defined(_TTHREAD_WIN32_) - if (cond->mEvents[_CONDITION_EVENT_ONE] != NULL) { - CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]); - } - if (cond->mEvents[_CONDITION_EVENT_ALL] != NULL) { - CloseHandle(cond->mEvents[_CONDITION_EVENT_ALL]); - } - DeleteCriticalSection(&cond->mWaitersCountLock); + if (cond->mEvents[_CONDITION_EVENT_ONE] != NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]); + } + if (cond->mEvents[_CONDITION_EVENT_ALL] != NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ALL]); + } + DeleteCriticalSection(&cond->mWaitersCountLock); #else - pthread_cond_destroy(cond); + pthread_cond_destroy(cond); #endif } -int cnd_signal(cnd_t *cond) { +int cnd_signal(cnd_t *cond) +{ #if defined(_TTHREAD_WIN32_) - int haveWaiters; + int haveWaiters; - /* Are there any waiters? */ - EnterCriticalSection(&cond->mWaitersCountLock); - haveWaiters = (cond->mWaitersCount > 0); - LeaveCriticalSection(&cond->mWaitersCountLock); + /* Are there any waiters? */ + EnterCriticalSection(&cond->mWaitersCountLock); + haveWaiters = (cond->mWaitersCount > 0); + LeaveCriticalSection(&cond->mWaitersCountLock); - /* If we have any waiting threads, send them a signal */ - if (haveWaiters) { - if (SetEvent(cond->mEvents[_CONDITION_EVENT_ONE]) == 0) { - return thrd_error; - } + /* If we have any waiting threads, send them a signal */ + if(haveWaiters) + { + if (SetEvent(cond->mEvents[_CONDITION_EVENT_ONE]) == 0) + { + return thrd_error; } + } - return thrd_success; + return thrd_success; #else - return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error; + return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error; #endif } -int cnd_broadcast(cnd_t *cond) { +int cnd_broadcast(cnd_t *cond) +{ #if defined(_TTHREAD_WIN32_) - int haveWaiters; + int haveWaiters; - /* Are there any waiters? */ - EnterCriticalSection(&cond->mWaitersCountLock); - haveWaiters = (cond->mWaitersCount > 0); - LeaveCriticalSection(&cond->mWaitersCountLock); + /* Are there any waiters? */ + EnterCriticalSection(&cond->mWaitersCountLock); + haveWaiters = (cond->mWaitersCount > 0); + LeaveCriticalSection(&cond->mWaitersCountLock); - /* If we have any waiting threads, send them a signal */ - if (haveWaiters) { - if (SetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) { - return thrd_error; - } + /* If we have any waiting threads, send them a signal */ + if(haveWaiters) + { + if (SetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) + { + return thrd_error; } + } - return thrd_success; + return thrd_success; #else - return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error; + return pthread_cond_broadcast(cond) == 0 ? thrd_success : thrd_error; #endif } #if defined(_TTHREAD_WIN32_) - -static int _cnd_timedwait_win32(cnd_t *cond, mtx_t *mtx, DWORD timeout) { - int result, lastWaiter; - - /* Increment number of waiters */ - EnterCriticalSection(&cond->mWaitersCountLock); - ++cond->mWaitersCount; - LeaveCriticalSection(&cond->mWaitersCountLock); - - /* Release the mutex while waiting for the condition (will decrease - the number of waiters when done)... */ - mtx_unlock(mtx); - - /* Wait for either event to become signaled due to cnd_signal() or - cnd_broadcast() being called */ - result = WaitForMultipleObjects(2, cond->mEvents, FALSE, timeout); - if (result == WAIT_TIMEOUT) { - return thrd_timeout; - } else if (result == (int) WAIT_FAILED) { - return thrd_error; - } - - /* Check if we are the last waiter */ - EnterCriticalSection(&cond->mWaitersCountLock); - --cond->mWaitersCount; - lastWaiter = (result == (WAIT_OBJECT_0 + _CONDITION_EVENT_ALL)) && - (cond->mWaitersCount == 0); - LeaveCriticalSection(&cond->mWaitersCountLock); - - /* If we are the last waiter to be notified to stop waiting, reset the event */ - if (lastWaiter) { - if (ResetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) { - return thrd_error; - } +static int _cnd_timedwait_win32(cnd_t *cond, mtx_t *mtx, DWORD timeout) +{ + DWORD result; + int lastWaiter; + + /* Increment number of waiters */ + EnterCriticalSection(&cond->mWaitersCountLock); + ++ cond->mWaitersCount; + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* Release the mutex while waiting for the condition (will decrease + the number of waiters when done)... */ + mtx_unlock(mtx); + + /* Wait for either event to become signaled due to cnd_signal() or + cnd_broadcast() being called */ + result = WaitForMultipleObjects(2, cond->mEvents, FALSE, timeout); + if (result == WAIT_TIMEOUT) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_timedout; + } + else if (result == WAIT_FAILED) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_error; + } + + /* Check if we are the last waiter */ + EnterCriticalSection(&cond->mWaitersCountLock); + -- cond->mWaitersCount; + lastWaiter = (result == (WAIT_OBJECT_0 + _CONDITION_EVENT_ALL)) && + (cond->mWaitersCount == 0); + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* If we are the last waiter to be notified to stop waiting, reset the event */ + if (lastWaiter) + { + if (ResetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_error; } + } - /* Re-acquire the mutex */ - mtx_lock(mtx); + /* Re-acquire the mutex */ + mtx_lock(mtx); - return thrd_success; + return thrd_success; } - #endif -int cnd_wait(cnd_t *cond, mtx_t *mtx) { +int cnd_wait(cnd_t *cond, mtx_t *mtx) +{ #if defined(_TTHREAD_WIN32_) - return _cnd_timedwait_win32(cond, mtx, INFINITE); + return _cnd_timedwait_win32(cond, mtx, INFINITE); #else - return pthread_cond_wait(cond, mtx) == 0 ? thrd_success : thrd_error; + return pthread_cond_wait(cond, mtx) == 0 ? thrd_success : thrd_error; #endif } -int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts) { +int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts) +{ #if defined(_TTHREAD_WIN32_) - struct timespec now; - if (clock_gettime(CLOCK_REALTIME, &now) == 0) { - DWORD delta = (DWORD) ((ts->tv_sec - now.tv_sec) * 1000 + - (ts->tv_nsec - now.tv_nsec + 500000) / 1000000); - return _cnd_timedwait_win32(cond, mtx, delta); - } else - return thrd_error; + struct timespec now; + if (timespec_get(&now, TIME_UTC) == TIME_UTC) + { + unsigned long long nowInMilliseconds = now.tv_sec * 1000 + now.tv_nsec / 1000000; + unsigned long long tsInMilliseconds = ts->tv_sec * 1000 + ts->tv_nsec / 1000000; + DWORD delta = (tsInMilliseconds > nowInMilliseconds) ? + (DWORD)(tsInMilliseconds - nowInMilliseconds) : 0; + return _cnd_timedwait_win32(cond, mtx, delta); + } + else + return thrd_error; #else - int ret; - ret = pthread_cond_timedwait(cond, mtx, ts); - if (ret == ETIMEDOUT) + int ret; + ret = pthread_cond_timedwait(cond, mtx, ts); + if (ret == ETIMEDOUT) + { + return thrd_timedout; + } + return ret == 0 ? thrd_success : thrd_error; +#endif +} + +#if defined(_TTHREAD_WIN32_) +struct TinyCThreadTSSData { + void* value; + tss_t key; + struct TinyCThreadTSSData* next; +}; + +static tss_dtor_t _tinycthread_tss_dtors[1088] = { NULL, }; + +static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_head = NULL; +static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_tail = NULL; + +static void _tinycthread_tss_cleanup (void); + +static void _tinycthread_tss_cleanup (void) { + struct TinyCThreadTSSData* data; + int iteration; + unsigned int again = 1; + void* value; + + for (iteration = 0 ; iteration < TSS_DTOR_ITERATIONS && again > 0 ; iteration++) + { + again = 0; + for (data = _tinycthread_tss_head ; data != NULL ; data = data->next) { - return thrd_timeout; + if (data->value != NULL) + { + value = data->value; + data->value = NULL; + + if (_tinycthread_tss_dtors[data->key] != NULL) + { + again = 1; + _tinycthread_tss_dtors[data->key](value); + } + } } - return ret == 0 ? thrd_success : thrd_error; -#endif + } + + while (_tinycthread_tss_head != NULL) { + data = _tinycthread_tss_head->next; + free (_tinycthread_tss_head); + _tinycthread_tss_head = data; + } + _tinycthread_tss_head = NULL; + _tinycthread_tss_tail = NULL; +} + +static void NTAPI _tinycthread_tss_callback(PVOID h, DWORD dwReason, PVOID pv) +{ + (void)h; + (void)pv; + + if (_tinycthread_tss_head != NULL && (dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH)) + { + _tinycthread_tss_cleanup(); + } } +#if defined(_MSC_VER) + #ifdef _M_X64 + #pragma const_seg(".CRT$XLB") + #else + #pragma data_seg(".CRT$XLB") + #endif + PIMAGE_TLS_CALLBACK p_thread_callback = _tinycthread_tss_callback; + #ifdef _M_X64 + #pragma data_seg() + #else + #pragma const_seg() + #endif +#else + PIMAGE_TLS_CALLBACK p_thread_callback __attribute__((section(".CRT$XLB"))) = _tinycthread_tss_callback; +#endif + +#endif /* defined(_TTHREAD_WIN32_) */ /** Information to pass to the new thread (what to run). */ typedef struct { - thrd_start_t mFunction; /**< Pointer to the function to be executed. */ - void *mArg; /**< Function argument for the thread function. */ + thrd_start_t mFunction; /**< Pointer to the function to be executed. */ + void * mArg; /**< Function argument for the thread function. */ } _thread_start_info; /* Thread wrapper function. */ #if defined(_TTHREAD_WIN32_) - -static unsigned WINAPI _thrd_wrapper_function(void *aArg) +static DWORD WINAPI _thrd_wrapper_function(LPVOID aArg) #elif defined(_TTHREAD_POSIX_) static void * _thrd_wrapper_function(void * aArg) #endif { - thrd_start_t fun; - void *arg; - int res; -#if defined(_TTHREAD_POSIX_) - void *pres; -#endif + thrd_start_t fun; + void *arg; + int res; - /* Get thread startup information */ - _thread_start_info *ti = (_thread_start_info *) aArg; - fun = ti->mFunction; - arg = ti->mArg; + /* Get thread startup information */ + _thread_start_info *ti = (_thread_start_info *) aArg; + fun = ti->mFunction; + arg = ti->mArg; - /* The thread is responsible for freeing the startup information */ - free((void *) ti); + /* The thread is responsible for freeing the startup information */ + free((void *)ti); - /* Call the actual client thread function */ - res = fun(arg); + /* Call the actual client thread function */ + res = fun(arg); #if defined(_TTHREAD_WIN32_) - return res; + if (_tinycthread_tss_head != NULL) + { + _tinycthread_tss_cleanup(); + } + + return (DWORD)res; #else - pres = malloc(sizeof(int)); - if (pres != NULL) - { - *(int*)pres = res; - } - return pres; + return (void*)(intptr_t)res; #endif } -int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) { - /* Fill out the thread startup information (passed to the thread wrapper, - which will eventually free it) */ - _thread_start_info *ti = (_thread_start_info *) malloc(sizeof(_thread_start_info)); - if (ti == NULL) { - return thrd_nomem; - } - ti->mFunction = func; - ti->mArg = arg; - - /* Create the thread */ +int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) +{ + /* Fill out the thread startup information (passed to the thread wrapper, + which will eventually free it) */ + _thread_start_info* ti = (_thread_start_info*)malloc(sizeof(_thread_start_info)); + if (ti == NULL) + { + return thrd_nomem; + } + ti->mFunction = func; + ti->mArg = arg; + + /* Create the thread */ #if defined(_TTHREAD_WIN32_) - *thr = (HANDLE) _beginthreadex(NULL, 0, _thrd_wrapper_function, (void *) ti, 0, NULL); + *thr = CreateThread(NULL, 0, _thrd_wrapper_function, (LPVOID) ti, 0, NULL); #elif defined(_TTHREAD_POSIX_) - if(pthread_create(thr, NULL, _thrd_wrapper_function, (void *)ti) != 0) - { - *thr = 0; - } + if(pthread_create(thr, NULL, _thrd_wrapper_function, (void *)ti) != 0) + { + *thr = 0; + } #endif - /* Did we fail to create the thread? */ - if (!*thr) { - free(ti); - return thrd_error; - } + /* Did we fail to create the thread? */ + if(!*thr) + { + free(ti); + return thrd_error; + } - return thrd_success; + return thrd_success; } -thrd_t thrd_current(void) { +thrd_t thrd_current(void) +{ #if defined(_TTHREAD_WIN32_) - return GetCurrentThread(); + return GetCurrentThread(); #else - return pthread_self(); + return pthread_self(); #endif } -int thrd_detach(thrd_t thr) { - /* FIXME! */ - (void) thr; - return thrd_error; +int thrd_detach(thrd_t thr) +{ +#if defined(_TTHREAD_WIN32_) + /* https://stackoverflow.com/questions/12744324/how-to-detach-a-thread-on-windows-c#answer-12746081 */ + return CloseHandle(thr) != 0 ? thrd_success : thrd_error; +#else + return pthread_detach(thr) == 0 ? thrd_success : thrd_error; +#endif } -int thrd_equal(thrd_t thr0, thrd_t thr1) { +int thrd_equal(thrd_t thr0, thrd_t thr1) +{ #if defined(_TTHREAD_WIN32_) - return thr0 == thr1; + return GetThreadId(thr0) == GetThreadId(thr1); #else - return pthread_equal(thr0, thr1); + return pthread_equal(thr0, thr1); #endif } -void thrd_exit(int res) { +void thrd_exit(int res) +{ #if defined(_TTHREAD_WIN32_) - ExitThread(res); + if (_tinycthread_tss_head != NULL) + { + _tinycthread_tss_cleanup(); + } + + ExitThread((DWORD)res); #else - void *pres = malloc(sizeof(int)); - if (pres != NULL) - { - *(int*)pres = res; - } - pthread_exit(pres); + pthread_exit((void*)(intptr_t)res); #endif } -int thrd_join(thrd_t thr, int *res) { +int thrd_join(thrd_t thr, int *res) +{ #if defined(_TTHREAD_WIN32_) - if (WaitForSingleObject(thr, INFINITE) == WAIT_FAILED) { - return thrd_error; - } - if (res != NULL) { - DWORD dwRes; - GetExitCodeThread(thr, &dwRes); - *res = dwRes; - } -#elif defined(_TTHREAD_POSIX_) - void *pres; - int ires = 0; - if (pthread_join(thr, &pres) != 0) - { - return thrd_error; - } - if (pres != NULL) + DWORD dwRes; + + if (WaitForSingleObject(thr, INFINITE) == WAIT_FAILED) + { + return thrd_error; + } + if (res != NULL) + { + if (GetExitCodeThread(thr, &dwRes) != 0) { - ires = *(int*)pres; - free(pres); + *res = (int) dwRes; } - if (res != NULL) + else { - *res = ires; + return thrd_error; } + } + CloseHandle(thr); +#elif defined(_TTHREAD_POSIX_) + void *pres; + if (pthread_join(thr, &pres) != 0) + { + return thrd_error; + } + if (res != NULL) + { + *res = (int)(intptr_t)pres; + } #endif - return thrd_success; + return thrd_success; } -int thrd_sleep(const struct timespec *time_point, struct timespec *remaining) { - struct timespec now; -#if defined(_TTHREAD_WIN32_) - DWORD delta; +int thrd_sleep(const struct timespec *duration, struct timespec *remaining) +{ +#if !defined(_TTHREAD_WIN32_) + int res = nanosleep(duration, remaining); + if (res == 0) { + return 0; + } else if (errno == EINTR) { + return -1; + } else { + return -2; + } #else - long delta; -#endif + struct timespec start; + DWORD t; - /* Get the current time */ - if (clock_gettime(CLOCK_REALTIME, &now) != 0) - return -2; // FIXME: Some specific error code? + timespec_get(&start, TIME_UTC); -#if defined(_TTHREAD_WIN32_) - /* Delta in milliseconds */ - long long int d = ((time_point->tv_sec - now.tv_sec) * 1000 + - (time_point->tv_nsec - now.tv_nsec + 500000) / 1000000); - if (d > 0) { - delta = d; - Sleep(delta); - } -#else - /* Delta in microseconds */ - delta = (time_point->tv_sec - now.tv_sec) * 1000000L + - (time_point->tv_nsec - now.tv_nsec + 500L) / 1000L; + t = SleepEx((DWORD)(duration->tv_sec * 1000 + + duration->tv_nsec / 1000000 + + (((duration->tv_nsec % 1000000) == 0) ? 0 : 1)), + TRUE); - /* On some systems, the usleep argument must be < 1000000 */ - while (delta > 999999L) - { - usleep(999999); - delta -= 999999L; - } - if (delta > 0L) - { - usleep((useconds_t)delta); + if (t == 0) { + return 0; + } else { + if (remaining != NULL) { + timespec_get(remaining, TIME_UTC); + remaining->tv_sec -= start.tv_sec; + remaining->tv_nsec -= start.tv_nsec; + if (remaining->tv_nsec < 0) + { + remaining->tv_nsec += 1000000000; + remaining->tv_sec -= 1; + } } + + return (t == WAIT_IO_COMPLETION) ? -1 : -2; + } #endif +} - /* We don't support waking up prematurely (yet) */ - if (remaining) { - remaining->tv_sec = 0; - remaining->tv_nsec = 0; - } - return 0; +void thrd_yield(void) +{ +#if defined(_TTHREAD_WIN32_) + Sleep(0); +#else + sched_yield(); +#endif } -void thrd_yield(void) { +int tss_create(tss_t *key, tss_dtor_t dtor) +{ #if defined(_TTHREAD_WIN32_) - Sleep(0); + *key = TlsAlloc(); + if (*key == TLS_OUT_OF_INDEXES) + { + return thrd_error; + } + _tinycthread_tss_dtors[*key] = dtor; #else - sched_yield(); + if (pthread_key_create(key, dtor) != 0) + { + return thrd_error; + } #endif + return thrd_success; } -int tss_create(tss_t *key, tss_dtor_t dtor) { +void tss_delete(tss_t key) +{ #if defined(_TTHREAD_WIN32_) - /* FIXME: The destructor function is not supported yet... */ - if (dtor != NULL) { - return thrd_error; + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*) TlsGetValue (key); + struct TinyCThreadTSSData* prev = NULL; + if (data != NULL) + { + if (data == _tinycthread_tss_head) + { + _tinycthread_tss_head = data->next; } - *key = TlsAlloc(); - if (*key == TLS_OUT_OF_INDEXES) { - return thrd_error; + else + { + prev = _tinycthread_tss_head; + if (prev != NULL) + { + while (prev->next != data) + { + prev = prev->next; + } + } } -#else - if (pthread_key_create(key, dtor) != 0) + + if (data == _tinycthread_tss_tail) { - return thrd_error; + _tinycthread_tss_tail = prev; } -#endif - return thrd_success; -} -void tss_delete(tss_t key) { -#if defined(_TTHREAD_WIN32_) - TlsFree(key); + free (data); + } + _tinycthread_tss_dtors[key] = NULL; + TlsFree(key); #else - pthread_key_delete(key); + pthread_key_delete(key); #endif } -void *tss_get(tss_t key) { +void *tss_get(tss_t key) +{ #if defined(_TTHREAD_WIN32_) - return TlsGetValue(key); + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key); + if (data == NULL) + { + return NULL; + } + return data->value; #else - return pthread_getspecific(key); + return pthread_getspecific(key); #endif } -int tss_set(tss_t key, void *val) { +int tss_set(tss_t key, void *val) +{ #if defined(_TTHREAD_WIN32_) - if (TlsSetValue(key, val) == 0) { - return thrd_error; - } -#else - if (pthread_setspecific(key, val) != 0) + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key); + if (data == NULL) + { + data = (struct TinyCThreadTSSData*)malloc(sizeof(struct TinyCThreadTSSData)); + if (data == NULL) { return thrd_error; + } + + data->value = NULL; + data->key = key; + data->next = NULL; + + if (_tinycthread_tss_tail != NULL) + { + _tinycthread_tss_tail->next = data; } + else + { + _tinycthread_tss_tail = data; + } + + if (_tinycthread_tss_head == NULL) + { + _tinycthread_tss_head = data; + } + + if (!TlsSetValue(key, data)) + { + free (data); + return thrd_error; + } + } + data->value = val; +#else + if (pthread_setspecific(key, val) != 0) + { + return thrd_error; + } #endif - return thrd_success; + return thrd_success; } -#if defined(_TTHREAD_EMULATE_CLOCK_GETTIME_) +#if defined(_TTHREAD_EMULATE_TIMESPEC_GET_) +int _tthread_timespec_get(struct timespec *ts, int base) +{ +#if defined(_TTHREAD_WIN32_) + struct _timeb tb; +#elif !defined(CLOCK_REALTIME) + struct timeval tv; +#endif + + if (base != TIME_UTC) + { + return 0; + } -int _tthread_clock_gettime(clockid_t clk_id, struct timespec *ts) { #if defined(_TTHREAD_WIN32_) - struct _timeb tb; - _ftime(&tb); - ts->tv_sec = (time_t) tb.time; - ts->tv_nsec = 1000000L * (long) tb.millitm; + _ftime_s(&tb); + ts->tv_sec = (time_t)tb.time; + ts->tv_nsec = 1000000L * (long)tb.millitm; +#elif defined(CLOCK_REALTIME) + base = (clock_gettime(CLOCK_REALTIME, ts) == 0) ? base : 0; #else - struct timeval tv; - gettimeofday(&tv, NULL); - ts->tv_sec = (time_t)tv.tv_sec; - ts->tv_nsec = 1000L * (long)tv.tv_usec; + gettimeofday(&tv, NULL); + ts->tv_sec = (time_t)tv.tv_sec; + ts->tv_nsec = 1000L * (long)tv.tv_usec; #endif - return 0; + + return base; } +#endif /* _TTHREAD_EMULATE_TIMESPEC_GET_ */ -#endif // _TTHREAD_EMULATE_CLOCK_GETTIME_ +#if defined(_TTHREAD_WIN32_) +void call_once(once_flag *flag, void (*func)(void)) +{ + /* The idea here is that we use a spin lock (via the + InterlockedCompareExchange function) to restrict access to the + critical section until we have initialized it, then we use the + critical section to block until the callback has completed + execution. */ + while (flag->status < 3) + { + switch (flag->status) + { + case 0: + if (InterlockedCompareExchange (&(flag->status), 1, 0) == 0) { + InitializeCriticalSection(&(flag->lock)); + EnterCriticalSection(&(flag->lock)); + flag->status = 2; + func(); + flag->status = 3; + LeaveCriticalSection(&(flag->lock)); + return; + } + break; + case 1: + break; + case 2: + EnterCriticalSection(&(flag->lock)); + LeaveCriticalSection(&(flag->lock)); + break; + } + } +} +#endif /* defined(_TTHREAD_WIN32_) */ +#ifdef __cplusplus +} +#endif diff --git a/minijvm/c/utils/tinycthread.h b/minijvm/c/utils/tinycthread.h index 3d54cf675..2fc7f628a 100755 --- a/minijvm/c/utils/tinycthread.h +++ b/minijvm/c/utils/tinycthread.h @@ -1,5 +1,6 @@ -/* -*- mode: vm; tab-width: 2; indent-tabs-mode: nil; -*- -Copyright (vm) 2012 Marcus Geelnard +/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*- +Copyright (c) 2012 Marcus Geelnard +Copyright (c) 2013-2016 Evan Nemerson This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -27,6 +28,7 @@ freely, subject to the following restrictions: #ifdef __cplusplus extern "C" { #endif + /** * @file * @mainpage TinyCThread API Reference @@ -74,6 +76,7 @@ extern "C" { #undef _XOPEN_SOURCE #define _XOPEN_SOURCE 500 #endif + #define _XPG6 #endif /* Generic includes */ @@ -81,7 +84,6 @@ extern "C" { /* Platform specific includes */ #if defined(_TTHREAD_POSIX_) - #include #include #elif defined(_TTHREAD_WIN32_) #ifndef WIN32_LEAN_AND_MEAN @@ -95,47 +97,37 @@ extern "C" { #endif #endif -/* Workaround for missing TIME_UTC: If time.h doesn't provide TIME_UTC, - it's quite likely that libc does not support it either. Hence, fall back to - the only other supported time specifier: CLOCK_REALTIME (and if that fails, - we're probably emulating clock_gettime anyway, so anything goes). */ -#ifndef TIME_UTC - #ifdef CLOCK_REALTIME - #define TIME_UTC CLOCK_REALTIME - #else - #define TIME_UTC 0 - #endif +/* Compiler-specific information */ +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define TTHREAD_NORETURN _Noreturn +#elif defined(__GNUC__) + #define TTHREAD_NORETURN __attribute__((__noreturn__)) +#else + #define TTHREAD_NORETURN #endif -/* Workaround for missing clock_gettime (most Windows compilers, afaik) */ -#if defined(_TTHREAD_WIN32_) || defined(__APPLE_CC__) -#define _TTHREAD_EMULATE_CLOCK_GETTIME_ -/* Emulate struct timespec */ +/* If TIME_UTC is missing, provide it and provide a wrapper for + timespec_get. */ +#ifndef TIME_UTC +#define TIME_UTC 1 +#define _TTHREAD_EMULATE_TIMESPEC_GET_ + #if defined(_TTHREAD_WIN32_) -struct _ttherad_timespec { +struct _tthread_timespec { time_t tv_sec; long tv_nsec; }; -#define timespec _ttherad_timespec +#define timespec _tthread_timespec #endif -/* Emulate clockid_t */ -typedef int _tthread_clockid_t; -#define clockid_t _tthread_clockid_t - -/* Emulate clock_gettime */ -int _tthread_clock_gettime(clockid_t clk_id, struct timespec *ts); -#define clock_gettime _tthread_clock_gettime -#ifndef CLOCK_REALTIME - #define CLOCK_REALTIME 0 -#endif +int _tthread_timespec_get(struct timespec *ts, int base); +#define timespec_get _tthread_timespec_get #endif - /** TinyCThread version (major number). */ #define TINYCTHREAD_VERSION_MAJOR 1 /** TinyCThread version (minor number). */ -#define TINYCTHREAD_VERSION_MINOR 1 +#define TINYCTHREAD_VERSION_MINOR 2 /** TinyCThread version (full version). */ #define TINYCTHREAD_VERSION (TINYCTHREAD_VERSION_MAJOR * 100 + TINYCTHREAD_VERSION_MINOR) @@ -154,41 +146,49 @@ int _tthread_clock_gettime(clockid_t clk_id, struct timespec *ts); * @note This directive is currently not supported on Mac OS X (it will give * a compiler error), since compile-time TLS is not supported in the Mac OS X * executable format. Also, some older versions of MinGW (before GCC 4.x) do -* not support this directive. +* not support this directive, nor does the Tiny C Compiler. * @hideinitializer */ -/* FIXME: Check for a PROPER value of __STDC_VERSION__ to know if we have C11 */ #if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201102L)) && !defined(_Thread_local) #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) #define _Thread_local __thread #else #define _Thread_local __declspec(thread) #endif +#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && (((__GNUC__ << 8) | __GNUC_MINOR__) < ((4 << 8) | 9)) + #define _Thread_local __thread #endif /* Macros */ -#define TSS_DTOR_ITERATIONS 0 +#if defined(_TTHREAD_WIN32_) +#define TSS_DTOR_ITERATIONS (4) +#else +#define TSS_DTOR_ITERATIONS PTHREAD_DESTRUCTOR_ITERATIONS +#endif /* Function return values */ #define thrd_error 0 /**< The requested operation failed */ #define thrd_success 1 /**< The requested operation succeeded */ -#define thrd_timeout 2 /**< The time specified in the call was reached without acquiring the requested resource */ +#define thrd_timedout 2 /**< The time specified in the call was reached without acquiring the requested resource */ #define thrd_busy 3 /**< The requested operation failed because a tesource requested by a test and return function is already in use */ #define thrd_nomem 4 /**< The requested operation failed because it was unable to allocate memory */ /* Mutex types */ -#define mtx_plain 1 -#define mtx_timed 2 -#define mtx_try 4 -#define mtx_recursive 8 +#define mtx_plain 0 +#define mtx_timed 1 +#define mtx_recursive 2 /* Mutex */ #if defined(_TTHREAD_WIN32_) typedef struct { - CRITICAL_SECTION mHandle; /* Critical section handle */ + union { + CRITICAL_SECTION cs; /* Critical section handle (used for non-timed mutexes) */ + HANDLE mut; /* Mutex handle (used for timed mutex) */ + } mHandle; /* Mutex handle */ int mAlreadyLocked; /* TRUE if the mutex is already locked */ int mRecursive; /* TRUE if the mutex is recursive */ + int mTimed; /* TRUE if the mutex is timed */ } mtx_t; #else typedef pthread_mutex_t mtx_t; @@ -199,10 +199,8 @@ typedef pthread_mutex_t mtx_t; * @param type Bit-mask that must have one of the following six values: * @li @c mtx_plain for a simple non-recursive mutex * @li @c mtx_timed for a non-recursive mutex that supports timeout -* @li @c mtx_try for a non-recursive mutex that supports test and return * @li @c mtx_plain | @c mtx_recursive (same as @c mtx_plain, but recursive) * @li @c mtx_timed | @c mtx_recursive (same as @c mtx_timed, but recursive) -* @li @c mtx_try | @c mtx_recursive (same as @c mtx_try, but recursive) * @return @ref thrd_success on success, or @ref thrd_error if the request could * not be honored. */ @@ -223,7 +221,14 @@ void mtx_destroy(mtx_t *mtx); */ int mtx_lock(mtx_t *mtx); -/** NOT YET IMPLEMENTED. +/** Lock the given mutex, or block until a specific point in time. +* Blocks until either the given mutex can be locked, or the specified TIME_UTC +* based time. +* @param mtx A mutex object. +* @param ts A UTC based calendar time +* @return @ref The mtx_timedlock function returns thrd_success on success, or +* thrd_timedout if the time specified was reached without acquiring the +* requested resource, or thrd_error if the request could not be honored. */ int mtx_timedlock(mtx_t *mtx, const struct timespec *ts); @@ -349,7 +354,8 @@ int thrd_create(thrd_t *thr, thrd_start_t func, void *arg); */ thrd_t thrd_current(void); -/** NOT YET IMPLEMENTED. +/** Dispose of any resources allocated to the thread when that thread exits. + * @return thrd_success, or thrd_error on error */ int thrd_detach(thrd_t thr); @@ -363,7 +369,7 @@ int thrd_equal(thrd_t thr0, thrd_t thr1); /** Terminate execution of the calling thread. * @param res Result code of the calling thread. */ -void thrd_exit(int res); +TTHREAD_NORETURN void thrd_exit(int res); /** Wait for a thread to terminate. * The function joins the given thread with the current thread by blocking @@ -378,15 +384,16 @@ int thrd_join(thrd_t thr, int *res); /** Put the calling thread to sleep. * Suspend execution of the calling thread. -* @param time_point A point in time at which the thread will resume (absolute time). -* @param remaining If non-NULL, this parameter will hold the remaining time until -* time_point upon return. This will typically be zero, but if -* the thread was woken up by a signal that is not ignored before -* time_point was reached @c remaining will hold a positive -* time. -* @return 0 (zero) on successful sleep, or -1 if an interrupt occurred. +* @param duration Interval to sleep for +* @param remaining If non-NULL, this parameter will hold the remaining +* time until time_point upon return. This will +* typically be zero, but if the thread was woken up +* by a signal that is not ignored before duration was +* reached @c remaining will hold a positive time. +* @return 0 (zero) on successful sleep, -1 if an interrupt occurred, +* or a negative value if the operation fails. */ -int thrd_sleep(const struct timespec *time_point, struct timespec *remaining); +int thrd_sleep(const struct timespec *duration, struct timespec *remaining); /** Yield execution to another thread. * Permit other threads to run, even if the current thread would ordinarily @@ -412,9 +419,11 @@ typedef void (*tss_dtor_t)(void *val); * @param dtor Destructor function. This can be NULL. * @return @ref thrd_success on success, or @ref thrd_error if the request could * not be honored. -* @note The destructor function is not supported under Windows. If @c dtor is -* not NULL when calling this function under Windows, the function will fail -* and return @ref thrd_error. +* @note On Windows, the @c dtor will definitely be called when +* appropriate for threads created with @ref thrd_create. It will be +* called for other threads in most cases, the possible exception being +* for DLLs loaded with LoadLibraryEx. In order to be certain, you +* should use @ref thrd_create whenever possible. */ int tss_create(tss_t *key, tss_dtor_t dtor); @@ -441,8 +450,30 @@ void *tss_get(tss_t key); */ int tss_set(tss_t key, void *val); +#if defined(_TTHREAD_WIN32_) + typedef struct { + LONG volatile status; + CRITICAL_SECTION lock; + } once_flag; + #define ONCE_FLAG_INIT {0,} +#else + #define once_flag pthread_once_t + #define ONCE_FLAG_INIT PTHREAD_ONCE_INIT +#endif + +/** Invoke a callback exactly once + * @param flag Flag used to ensure the callback is invoked exactly + * once. + * @param func Callback to invoke. + */ +#if defined(_TTHREAD_WIN32_) + void call_once(once_flag *flag, void (*func)(void)); +#else + #define call_once(flag,func) pthread_once(flag,func) +#endif + #ifdef __cplusplus -}; +} #endif -#endif /* _TINYTHREAD_H_ */ +#endif /* _TINYTHREAD_H_ */