简体   繁体   English

V8与繁忙的脚本进行通信

[英]V8 communicating with busy script

Through v8 I am running javascript which is waiting on input from the engine side. 通过v8,我正在运行javascript,它正在等待引擎端的输入。 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. 问题在于Run()处于阻塞状态,并且标志从未设置为0。我还尝试在新线程中执行Run(),结果是出现访问冲突错误。

Is there a simple way to communicate with the running Javascript code? 有没有一种简单的方法可以与正在运行的Javascript代码进行通信? 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. 无需详细说明为什么上述方法不起作用:您要实现的目标是JavaScript中的多线程。 That does not exist. 那不存在。 JavaScript is a single-threaded language by design. JavaScript是设计上的单线程语言。 Concurrency is asynchronous. 并发是异步的。 And V8, like all other JS VMs, is a single-threaded engine. 和其他所有JS VM一样,V8是一个单线程引擎。 The only way multiple threads can access the same isolate is through a global mutax (cf. the Locker class). 多个线程访问同一隔离的唯一方法是通过全局mutax(请参阅Locker类)。

In short, trying to approach JavaScript with a programming approach based on multi-threading won't get you anywhere. 简而言之,尝试使用基于多线程的编程方法来处理JavaScript并不会帮助您。 It's not how it works. 这不是它的工作方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM