Skip to content

Commit

Permalink
n-api: add API for asynchronous functions
Browse files Browse the repository at this point in the history
Bundle a `uv_async_t`, a `uv_idle_t`, a `uv_mutex_t`, a `uv_cond_t`,
and a `v8::Persistent<v8::Function>` to make it possible to call into JS
from another thread. The API accepts a void data pointer and a callback
which will be invoked on the loop thread and which will receive the
`napi_value` representing the JavaScript function to call so as to
perform the call into JS. The callback is run inside a
`node::CallbackScope`.

A `std::queue<void*>` is used to store calls from the secondary
threads, and an idle loop is started by the `uv_async_t` callback on the
loop thread to drain the queue, calling into JS with each item.

Items can be added to the queue blockingly or non-blockingly.

The thread-safe function can be referenced or unreferenced, with the
same semantics as libuv handles.

Re: nodejs/help#1035
Re: nodejs/node#20964
Fixes: nodejs/node#13512
  • Loading branch information
Gabriel Schulhof committed Jun 19, 2018
1 parent 772d390 commit 6a4f191
Show file tree
Hide file tree
Showing 8 changed files with 1,325 additions and 2 deletions.
30 changes: 30 additions & 0 deletions doc/api/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -1371,6 +1371,36 @@ multiple of the element size.
While calling `napi_create_typedarray()`, `(length * size_of_element) +
byte_offset` was larger than the length of given `buffer`.

<a id="ERR_NAPI_TSFN_CALL_JS"></a>
### ERR_NAPI_TSFN_CALL_JS

An error occurred while invoking the JavaScript portion of the thread-safe
function.

<a id="ERR_NAPI_TSFN_GET_UNDEFINED"></a>
### ERR_NAPI_TSFN_GET_UNDEFINED

An error occurred while attempting to retrieve the JavaScript `undefined`
value.

<a id="ERR_NAPI_TSFN_REMOVE_ENV_CLEANUP"></a>
### ERR_NAPI_TSFN_REMOVE_ENV_CLEANUP

An error occured while attempting to remove the environment cleanup handler.

<a id="ERR_NAPI_TSFN_START_IDLE_LOOP"></a>
### ERR_NAPI_TSFN_START_IDLE_LOOP

On the main thread, values are removed from the queue associated with the
thread-safe function in an idle loop. This error indicates that an error
has occurred when attemping to start the loop.

<a id="ERR_NAPI_TSFN_STOP_IDLE_LOOP"></a>
### ERR_NAPI_TSFN_STOP_IDLE_LOOP

Once no more items are left in the queue, the idle loop must be suspended. This
error indicates that the idle loop has failed to stop.

<a id="ERR_NO_CRYPTO"></a>
### ERR_NO_CRYPTO

Expand Down
370 changes: 369 additions & 1 deletion doc/api/n-api.md

Large diffs are not rendered by default.

Loading

0 comments on commit 6a4f191

Please sign in to comment.