From 55e948100971f9c384b8ce3f4f4891f4868ddc14 Mon Sep 17 00:00:00 2001 From: Gabriel Schulhof Date: Mon, 13 Apr 2020 11:08:13 -0700 Subject: [PATCH] n-api: fix win32 main thread detection `uv_thread_self()` works on Windows only for threads created using `uv_thread_start()` because libuv does not use `GetCurrentThreadId()` for threads that were created otherwise. `uv_thread_equal()` works correctly. Thus, on Windows we use `GetCurrentThreadId()` to compare the main thread with the current thread. Signed-off-by: Gabriel Schulhof --- src/node_api.cc | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/node_api.cc b/src/node_api.cc index 552538c6f05fcf..987fd6bc3a43c9 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -110,6 +110,15 @@ static inline void trigger_fatal_exception( node::errors::TriggerUncaughtException(env->isolate, local_err, local_msg); } +// `uv_thread_self()` returns 0 on Windows for threads that were not created +// using `uv_thread_start()`. Thus, for correct comparison, we need to use +// `GetCurrentThreadId()`. +#ifdef _WIN32 +#define THREAD_SELF_API reinterpret_cast(GetCurrentThreadId()) +#else +#define THREAD_SELF_API uv_thread_self() +#endif // _WIN32 + class ThreadSafeFunction : public node::AsyncResource { public: ThreadSafeFunction(v8::Local func, @@ -129,7 +138,7 @@ class ThreadSafeFunction : public node::AsyncResource { is_closing(false), context(context_), max_queue_size(max_queue_size_), - main_thread(uv_thread_self()), + main_thread(THREAD_SELF_API), env(env_), finalize_data(finalize_data_), finalize_cb(finalize_cb_), @@ -149,7 +158,7 @@ class ThreadSafeFunction : public node::AsyncResource { napi_status Push(void* data, napi_threadsafe_function_call_mode mode) { node::Mutex::ScopedLock lock(this->mutex); - uv_thread_t current_thread = uv_thread_self(); + uv_thread_t current_thread = THREAD_SELF_API; while (queue.size() >= max_queue_size && max_queue_size > 0 &&