Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

v8 Locker for multi thread

I have a function on main thread registering a callback from another native thread. Currently I'm encountering an issue that the native thread couldn't access to v8::Isolate. I searched around, seems we need to use v8::Locker for multi threading. I wonder how should we use this exactly? I'm new to V8 and couldn't find a good document to refer to.

The code:

Main thread:
void register_signaling_xml_callback(const Nan::FunctionCallbackInfo<v8::Value> &info) {
wa_call_register_signaling_xml_callback(details::wa_send_signaling_xml_cb, isolate);   // Register the callback on native thread;
....
// v8::Unlocker unlocker(isolate); If I remove this comment, native thread can access the isolate. However, the below line will crash. 
Nan::New(...);
}


Native thread:
int wa_send_signaling_data_cb(void *data, int len, void *userdata) {
  ....
  Nan::EscapableHandleScope scope; // This line will crash due to can not get v8::Isolate.
}

If I put v8::Locker v8Locker(isolate) and then v8::Unlocker unlocker(isolate); in the main thread, native thread can access the v8::Isolate. However, the main thread seems to loss the control over the isolate and Nan::New will lead to crash on main thread.

like image 479
Bruce Xinda Lin Avatar asked Apr 09 '19 23:04

Bruce Xinda Lin


People also ask

Is V8 multithreaded?

V8 Doesn't: V8 is a single threaded execution engine. It's built to run exactly one thread per JavaScript execution context. You can actually run two V8 engines in the same process — e.g. web-workers, but they won't share any variables or context like real threads.

Is Chrome V8 multithreaded?

Gears in Chrome uses V8 in the multi-threading environment.


1 Answers

Locks are usually made where the resource is used. In this case, the lock should happen in the callback function:

Native thread:
int wa_send_signaling_data_cb(void *data, int len, void *userdata) {
  ....
  v8::Locker v8Locker(); // no argument means default isolate
  Nan::EscapableHandleScope scope; // This line will crash due to can not get v8::Isolate.
}
like image 131
rmrrm Avatar answered Oct 25 '22 12:10

rmrrm