Skip to content

n-api: fix dead lock if multi push events #58724

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/node_api.cc
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ class ThreadSafeFunction : public node::AsyncResource {
dispatch_state(kDispatchIdle),
context(context_),
max_queue_size(max_queue_size_),
waiting_task_size(0),
env(env_),
finalize_data(finalize_data_),
finalize_cb(finalize_cb_),
Expand All @@ -238,12 +239,14 @@ class ThreadSafeFunction : public node::AsyncResource {
napi_status Push(void* data, napi_threadsafe_function_call_mode mode) {
node::Mutex::ScopedLock lock(this->mutex);

while (queue.size() >= max_queue_size && max_queue_size > 0 &&
while (max_queue_size > 0 && queue.size() >= max_queue_size &&
!is_closing) {
if (mode == napi_tsfn_nonblocking) {
return napi_queue_full;
}
waiting_task_size++;
cond->Wait(lock);
waiting_task_size--;
}

if (is_closing) {
Expand Down Expand Up @@ -385,7 +388,7 @@ class ThreadSafeFunction : public node::AsyncResource {
data = queue.front();
queue.pop();
popped_value = true;
if (size == max_queue_size && max_queue_size > 0) {
if (waiting_task_size > 0) {
cond->Signal(lock);
}
size--;
Expand Down Expand Up @@ -518,6 +521,7 @@ class ThreadSafeFunction : public node::AsyncResource {
// means we don't need the mutex to read them.
void* context;
size_t max_queue_size;
size_t waiting_task_size;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like it adds an extra variable when we could also just call Signal() unconditionally with the same effect? This class already has a very large state space (one of the worst examples I've seen), I'd try to avoid another piece of state even if its usage is localized to managing cond

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this approach seems acceptable. However, it may introduce unnecessary signal calls, which could incur additional performance overhead.


// These are variables accessed only from the loop thread.
v8impl::Persistent<v8::Function> ref;
Expand Down