Skip to content

Commit 84b7070

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 362b8c7 commit 84b7070

File tree

4 files changed

+18
-2
lines changed

4 files changed

+18
-2
lines changed

src/node.cc

+9
Original file line numberDiff line numberDiff line change
@@ -4670,6 +4670,15 @@ void RunAtExit(Environment* env) {
46704670
}
46714671

46724672

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

46754684

src/node.h

+4
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,10 @@ NODE_EXTERN void EmitBeforeExit(Environment* env);
248248
NODE_EXTERN int EmitExit(Environment* env);
249249
NODE_EXTERN void RunAtExit(Environment* env);
250250

251+
// This may return nullptr if the current v8::Context is not associated
252+
// with a Node instance.
253+
NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate);
254+
251255
/* Converts a unixtime to V8 Date */
252256
#define NODE_UNIXTIME_V8(t) v8::Date::New(v8::Isolate::GetCurrent(), \
253257
1000 * static_cast<double>(t))

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

+1-1
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

+4-1
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)