Skip to content
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

Scheduling an C++ event on the main thread #626

Closed
zander opened this issue Dec 7, 2019 · 3 comments
Closed

Scheduling an C++ event on the main thread #626

zander opened this issue Dec 7, 2019 · 3 comments

Comments

@zander
Copy link

zander commented Dec 7, 2019

Imagine an add-on that supplies a Search() method which is handled async in a native code using existing threads there.
It returns a Promise.

In the native code I at one time finish the search and want to call m_promise.Resolve(mainObject());

I get an error from nodejs if I call that in one of my search-engine threads, I don't get any error when I call this in the nodejs main thread.

The problem I'm trying to solve is to get an event planned on the JS main thread, which calls my native code and can do the Resolve() from above.

I may not get any Napi::Function from the user, so I can't use a threadsafefunction for this. I think.

Is there a simple way to schedule a call to a native method that I want to be executed on the main JS thread?

Thanks for any help you can give.

@legendecas
Copy link
Member

ThreadSafeFunction is not necessarily to be created with a Function -- it's optional, and we could use ThreadSafeFunction as an async handle to trigger some event on JS thread. Unfortunately, right now we have no constructors that receive no callback arguments. A workaround might be:

tsfn = Napi::ThreadSafeFunction::New(env,
    Function(), /** an empty `Napi::Function` */
    resource,
   resourceName,
   maxQueueSize,
   initialThreadCount,
   context,
   finalizeCallback,
   data);

tsfn.BlockingCall([=](Napi::Env env, Function callback /** callback is empty and shall not be used */) {
  /** Do anything you'd like on JS thread and do not use the `callback` parameter. */
});

Related: #544

@KevinEady
Copy link
Contributor

Be aware that the optional function callback is only supported in N-API 5. It is required in N-API 4. See "History" under the napi_create_threadsafe_function docs

@zander
Copy link
Author

zander commented Dec 23, 2019

Thanks, this seems to work on my nodejs13.0

I don't really know how to test on different versions. Looks like ubuntu/debian have really old versions of NodeJS in their stable releases, making testing on their platforms a bit of a no-go.

@zander zander closed this as completed Dec 23, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants