Skip to content

Commit fdd84c4

Browse files
addaleaxMylesBorins
authored andcommitted
src: add helper for addons to get the event loop
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 <[email protected]> Reviewed-By: Colin Ihrig <[email protected]>
1 parent 162ff56 commit fdd84c4

File tree

4 files changed

+18
-2
lines changed

4 files changed

+18
-2
lines changed

src/node.cc

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4672,6 +4672,15 @@ void RunAtExit(Environment* env) {
46724672
}
46734673

46744674

4675+
uv_loop_t* GetCurrentEventLoop(v8::Isolate* isolate) {
4676+
HandleScope handle_scope(isolate);
4677+
auto context = isolate->GetCurrentContext();
4678+
if (context.IsEmpty())
4679+
return nullptr;
4680+
return Environment::GetCurrent(context)->event_loop();
4681+
}
4682+
4683+
46754684
static uv_key_t thread_local_env;
46764685

46774686

src/node.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,10 @@ NODE_EXTERN void EmitBeforeExit(Environment* env);
227227
NODE_EXTERN int EmitExit(Environment* env);
228228
NODE_EXTERN void RunAtExit(Environment* env);
229229

230+
// This may return nullptr if the current v8::Context is not associated
231+
// with a Node instance.
232+
NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate);
233+
230234
/* Converts a unixtime to V8 Date */
231235
#define NODE_UNIXTIME_V8(t) v8::Date::New(v8::Isolate::GetCurrent(), \
232236
1000 * static_cast<double>(t))

test/addons/async-hello-world/binding.cc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ void Method(const v8::FunctionCallbackInfo<v8::Value>& args) {
7777
v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(args[1]);
7878
req->callback.Reset(isolate, callback);
7979

80-
uv_queue_work(uv_default_loop(),
80+
uv_queue_work(node::GetCurrentEventLoop(isolate),
8181
&req->req,
8282
DoAsync,
8383
(uv_after_work_cb)AfterAsync<use_makecallback>);

test/addons/callback-scope/binding.cc

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,10 @@ static void TestResolveAsync(const v8::FunctionCallbackInfo<v8::Value>& args) {
5252

5353
uv_work_t* req = new uv_work_t;
5454

55-
uv_queue_work(uv_default_loop(), req, [](uv_work_t*) {}, Callback);
55+
uv_queue_work(node::GetCurrentEventLoop(isolate),
56+
req,
57+
[](uv_work_t*) {},
58+
Callback);
5659
}
5760

5861
v8::Local<v8::Promise::Resolver> local =

0 commit comments

Comments
 (0)