Skip to content

Commit

Permalink
src: add helper for addons to get the event loop
Browse files Browse the repository at this point in the history
Add a utility functions for addons to use when they need
a reference to the current event loop.

Currently, `uv_default_loop()` works if the embedder is the
single-threaded default node executable, but even without
the presence of e.g. workers that might not really an API
guarantee for when Node is embedded.

PR-URL: #17109
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
  • Loading branch information
addaleax authored and MylesBorins committed Jan 15, 2018
1 parent 162ff56 commit fdd84c4
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 2 deletions.
9 changes: 9 additions & 0 deletions src/node.cc
Original file line number Diff line number Diff line change
Expand Up @@ -4672,6 +4672,15 @@ void RunAtExit(Environment* env) {
}


uv_loop_t* GetCurrentEventLoop(v8::Isolate* isolate) {
HandleScope handle_scope(isolate);
auto context = isolate->GetCurrentContext();
if (context.IsEmpty())
return nullptr;
return Environment::GetCurrent(context)->event_loop();
}


static uv_key_t thread_local_env;


Expand Down
4 changes: 4 additions & 0 deletions src/node.h
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,10 @@ NODE_EXTERN void EmitBeforeExit(Environment* env);
NODE_EXTERN int EmitExit(Environment* env);
NODE_EXTERN void RunAtExit(Environment* env);

// This may return nullptr if the current v8::Context is not associated
// with a Node instance.
NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate);

/* Converts a unixtime to V8 Date */
#define NODE_UNIXTIME_V8(t) v8::Date::New(v8::Isolate::GetCurrent(), \
1000 * static_cast<double>(t))
Expand Down
2 changes: 1 addition & 1 deletion test/addons/async-hello-world/binding.cc
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ void Method(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(args[1]);
req->callback.Reset(isolate, callback);

uv_queue_work(uv_default_loop(),
uv_queue_work(node::GetCurrentEventLoop(isolate),
&req->req,
DoAsync,
(uv_after_work_cb)AfterAsync<use_makecallback>);
Expand Down
5 changes: 4 additions & 1 deletion test/addons/callback-scope/binding.cc
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ static void TestResolveAsync(const v8::FunctionCallbackInfo<v8::Value>& args) {

uv_work_t* req = new uv_work_t;

uv_queue_work(uv_default_loop(), req, [](uv_work_t*) {}, Callback);
uv_queue_work(node::GetCurrentEventLoop(isolate),
req,
[](uv_work_t*) {},
Callback);
}

v8::Local<v8::Promise::Resolver> local =
Expand Down

0 comments on commit fdd84c4

Please sign in to comment.