Skip to content

Commit

Permalink
n-api: fix win32 main thread detection
Browse files Browse the repository at this point in the history
`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>
  • Loading branch information
Gabriel Schulhof committed Apr 13, 2020
1 parent 38bf1be commit 55e9481
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/node_api.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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<uv_thread_t>(GetCurrentThreadId())
#else
#define THREAD_SELF_API uv_thread_self()
#endif // _WIN32

class ThreadSafeFunction : public node::AsyncResource {
public:
ThreadSafeFunction(v8::Local<v8::Function> func,
Expand All @@ -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_),
Expand All @@ -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 &&
Expand Down

0 comments on commit 55e9481

Please sign in to comment.