V8 Función multiproceso
Estoy escribiendo un complemento Node y tengo problemas para intentar llamar a un objeto de función V8 desde un hilo de trabajo de C ++.
Mi complemento básicamente inicia un hilo de C ++ std :: y entra en un ciclo de espera usando WaitForSingleOject (), esto se activa por una aplicación diferente de C ++ (un complemento X-Plane) que escribe en un poco de memoria compartida. Estoy tratando de hacer que mi complemento Node se active cuando se señala el evento compartido de Windows y luego invoco una función de JavaScript que he registrado desde la aplicación de nodo, que a su vez pasará los datos que se originaron en X-Plane a Node y el mundo web.
He logrado averiguar cómo registrar una función de JavaScript y llamarla desde C ++, pero solo en el hilo principal de V8. Parece que no puedo encontrar una manera de llamar a la función desde el hilo std ::.
He intentado varios enfoques, objetos Locker (éxito variable), funciones persistentes (no funcionaron), guardar el objeto de aislamiento principal, ingresar / salir del aislamiento, pero si / cuando el código finalmente alcanza el objeto de función no es válido.
Obtengo resultados diferentes, que van desde fallar hasta congelarse dependiendo de si creo varios objetos de bloqueo y desbloqueo.
Soy totalmente nuevo en V8, así que no estoy seguro de estar haciendo nada bien. El código en cuestión es el siguiente:
¡Si alguien pudiera ayudarme, estaré eternamente agradecido!
float* mem = 0;
HANDLE event = NULL;
Isolate* thisIsolate;
void readSharedMemory()
{
//Isolate* isolate = Isolate::GetCurrent();
//HandleScope scope(isolate);
thisIsolate->Enter();
v8::Locker locker(thisIsolate);
v8::Isolate::Scope isolateScope(thisIsolate);
//HandleScope scope(thisIsolate);
//v8::Local<Value> myVal = v8::String::NewFromUtf8(isolate, "Plugin world");
v8::Local<Value> myVal = v8::Number::New(thisIsolate, *mem);
// If it get's this far 'myFunction' is not valid
bool isFun = myFunction->IsFunction();
isFun = callbackFunction->IsFunction();
v8::Context *thisContext = *(thisIsolate->GetCurrentContext());
myFunction->Call(thisContext->Global(), 1, &(Handle<Value>(myVal)));
}
void registerCallback(const FunctionCallbackInfo<Value>& args)
{
Isolate* isolate = Isolate::GetCurrent();
v8::Locker locker(isolate);
HandleScope scope(isolate);
/** Standard parameter checking code removed **/
// Various attempts at saving a function object
v8::Local<v8::Value> func = args[0];
bool isFun = func->IsFunction();
Handle<Object> callbackObject = args[0]->ToObject();
callbackFunction = Handle<Function>::Cast(callbackObject);
isFun = callbackFunction->IsFunction();
// save the function call object - This appears to work
myFunction = v8::Function::Cast(*callbackObject);
isFun = myFunction->IsFunction();
// Test the function - this works *without* the Unlocker object below
v8::Local<Value> myVal = v8::String::NewFromUtf8(isolate, "Plugin world");
myFunction->Call(isolate->GetCurrentContext()->Global(), 1, &(Handle<Value>(myVal)));
}
void threadFunc()
{
thisIsolate->Exit();
// If I include this unlocker, the function call test above fails.
// If I don't include it, the app hangs trying to create the locker in 'readSharedMemory()'
//v8::Unlocker unlocker(thisIsolate);
event = OpenEventW(EVENT_ALL_ACCESS, FALSE, L"Global\\myEventObject");
DWORD err = GetLastError();
//thisIsolate = v8::Isolate::New();
std::cout << "Hello from thread" << std::endl;
bool runThread = true;
while (runThread)
{
DWORD dwWaitResult;
DWORD waitTime = 60000;
dwWaitResult = WaitForSingleObject(event, waitTime);
err = GetLastError();
if (dwWaitResult == WAIT_TIMEOUT)
runThread = false;
// event has been signaled - continue
readSharedMemory();
}
}
void init(Handle<Object> exports)
{
/** NODE INITILISATION STUFF REMOVED **/
// save the isolate - Is this a safe thing to do?
thisIsolate = Isolate::GetCurrent();
//Launch a thread
eventThread = std::thread(threadFunc);
}