Skip to content

node-api ThreadsafeFunction is a leaky abstraction #38775

Open
@indutny

Description

@indutny

The premise of the API is that it should make it easy to call into a loop thread from any other thread(s). However, the semantics of napi_closing and finalize_cb mean that the API user need to wrap calls to call_threadsafe_function and release_threadsafe_function into a mutex, because they are inherently not threadsafe. This technically is documented, but very not obvious given the name of the API object.

I suggest that we change the API making it so that:

  • call_threadsafe_function never returns napi_closing and is safe to call up until internal thread_count drops to 0
  • release_threadsafe_function is safe to call up until internal thread_count drops to 0 irrespective of whether finalize_cb was called or not

Specifically, it sounds like for this to work we'll have to have an inner and outer classes for the ThreadsafeFunction. The inner would hold references to V8 objects and would be deleted on the loop/V8 thread during finalize_cb. The outer would be still accessible to the threads up until they all call the release method.

This is a breaking API change so I'd appreciate if we could have a discussion around that.

cc @nodejs/node-api @nodejs/addon-api @addaleax

See neon-bindings/neon#744 for particular woes on the API user side.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    node-apiIssues and PRs related to the Node-API.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions