Skip to content

Commit 55e9481

Browse files
author
Gabriel Schulhof
committed
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 <gabriel.schulhof@intel.com>
1 parent 38bf1be commit 55e9481

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

src/node_api.cc

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,15 @@ static inline void trigger_fatal_exception(
110110
node::errors::TriggerUncaughtException(env->isolate, local_err, local_msg);
111111
}
112112

113+
// `uv_thread_self()` returns 0 on Windows for threads that were not created
114+
// using `uv_thread_start()`. Thus, for correct comparison, we need to use
115+
// `GetCurrentThreadId()`.
116+
#ifdef _WIN32
117+
#define THREAD_SELF_API reinterpret_cast<uv_thread_t>(GetCurrentThreadId())
118+
#else
119+
#define THREAD_SELF_API uv_thread_self()
120+
#endif // _WIN32
121+
113122
class ThreadSafeFunction : public node::AsyncResource {
114123
public:
115124
ThreadSafeFunction(v8::Local<v8::Function> func,
@@ -129,7 +138,7 @@ class ThreadSafeFunction : public node::AsyncResource {
129138
is_closing(false),
130139
context(context_),
131140
max_queue_size(max_queue_size_),
132-
main_thread(uv_thread_self()),
141+
main_thread(THREAD_SELF_API),
133142
env(env_),
134143
finalize_data(finalize_data_),
135144
finalize_cb(finalize_cb_),
@@ -149,7 +158,7 @@ class ThreadSafeFunction : public node::AsyncResource {
149158

150159
napi_status Push(void* data, napi_threadsafe_function_call_mode mode) {
151160
node::Mutex::ScopedLock lock(this->mutex);
152-
uv_thread_t current_thread = uv_thread_self();
161+
uv_thread_t current_thread = THREAD_SELF_API;
153162

154163
while (queue.size() >= max_queue_size &&
155164
max_queue_size > 0 &&

0 commit comments

Comments
 (0)