質問

Through v8 I am running javascript which is waiting on input from the engine side. See below the simplified example. The problem is that Run() is blocking and flag is never set to 0. I also tried executing Run() in a new thread with Access Violation Errors as a result.

Is there a simple way to communicate with the running Javascript code? If it takes a separate Thread, what am I missing please?

Thank you very much in advance for your help!

int flag = 1;

static void getFlag(v8::Local<v8::String> property, 
    const v8::PropertyCallbackInfo<v8::Value>& info) {

    info.GetReturnValue().Set(flag);
}

...
objtemplate->SetAccessor(String::NewFromUtf8(isolate, "flag"), getFlag);
...
Handle<String> source = String::NewFromUtf8(isolate, "while(flag) { ... }");
Handle<Script> script = Script::Compile(source);
script->Run();

flag = 0;

This is my multi-thread approach:

void runner(v8::Handle<v8::Script> * script) {
    (*script)->Run();
}

CreateThread(0, 0, (LPTHREAD_START_ROUTINE) runner, (LPVOID) &script, 0, 0);
役に立ちましたか?

解決

Without going into details about why the above doesn't work: what you are trying to achieve is multi-threading in JavaScript. That does not exist. JavaScript is a single-threaded language by design. Concurrency is asynchronous. And V8, like all other JS VMs, is a single-threaded engine. The only way multiple threads can access the same isolate is through a global mutax (cf. the Locker class).

In short, trying to approach JavaScript with a programming approach based on multi-threading won't get you anywhere. It's not how it works.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top