From 3f4cd77a53637679fe00f7351085f9801f570eee Mon Sep 17 00:00:00 2001 From: Sebastian Reimers Date: Sun, 20 Oct 2024 09:34:24 +0200 Subject: [PATCH] thread/win32: fix thrd_current and thrd_equal handling --- include/re_thread.h | 3 ++- src/thread/win32.c | 25 +++++++++++++++++-------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/include/re_thread.h b/include/re_thread.h index 774754ae3..ac81647ce 100644 --- a/include/re_thread.h +++ b/include/re_thread.h @@ -22,6 +22,7 @@ #else #if defined(WIN32) +struct thrd_win32; #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN @@ -29,7 +30,7 @@ #include #define ONCE_FLAG_INIT INIT_ONCE_STATIC_INIT typedef INIT_ONCE once_flag; -typedef HANDLE thrd_t; +typedef struct thrd_win32 thrd_t; typedef CONDITION_VARIABLE cnd_t; typedef CRITICAL_SECTION mtx_t; typedef DWORD tss_t; diff --git a/src/thread/win32.c b/src/thread/win32.c index f177e6534..9aca00f6b 100644 --- a/src/thread/win32.c +++ b/src/thread/win32.c @@ -30,6 +30,11 @@ struct thread { void *arg; }; +struct thrd_win32 { + HANDLE hdl; + uint32_t id; +}; + static int dtor_register(tss_t key, tss_dtor_t dtor) { int i; @@ -107,7 +112,8 @@ int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) goto out; } - *thr = (thrd_t)handle; + *thr.hdl = (HANDLE)handle; + *thr.id = GetThreadId(handle); out: if (err) mem_deref(th); @@ -118,19 +124,22 @@ int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) int thrd_equal(thrd_t lhs, thrd_t rhs) { - return GetThreadId(lhs) == GetThreadId(rhs); + return lhs.id == rhs.id; } thrd_t thrd_current(void) { - return GetCurrentThread(); + /* GetCurrentThread() returns only a pseudo handle and can not used + * within other threads */ + thrd_t t = {.hdl = GetCurrentThread(), .id = GetCurrentThreadID()}; + return t; } int thrd_detach(thrd_t thr) { - CloseHandle(thr); + CloseHandle(thr.hdl); return thrd_success; } @@ -139,19 +148,19 @@ int thrd_join(thrd_t thr, int *res) { DWORD w, code; - w = WaitForSingleObject(thr, INFINITE); + w = WaitForSingleObject(thr.hdl, INFINITE); if (w != WAIT_OBJECT_0) return thrd_error; if (res) { - if (!GetExitCodeThread(thr, &code)) { - CloseHandle(thr); + if (!GetExitCodeThread(thr.hdl, &code)) { + CloseHandle(thr.hdl); return thrd_error; } *res = (int)code; } - CloseHandle(thr); + CloseHandle(thr.hdl); return thrd_success; }