我如何在v8中创建另一个线程
How can I create another thread in the v8
我想为v8::Script::Run设置超时时间。不幸的是,我对v8有一点经验。我明白我需要使用StartPreemtion + Loker + TerminateException。因此,v8::Script::Run应该在一个单独的线程中。执行时间的计算和控制应该在主线程中进行。如何在v8中创建另一个线程?请帮助我了解如何做。下面是我这样做的代码示例,但是线程的函数没有启动。
v8::Local<v8::Value> V8ExecuteString( v8::Handle<v8::String> source, v8::Handle<v8::String> filename )
{
// Compiling script
// ...
// End compiling script
DWORD start_tick = ::GetTickCount();
v8::Locker::StartPreemption( 1 );
{
v8::Unlocker unlocker;
boost::thread* th = new boost::thread( [&] () {
v8::Locker locker;
v8::HandleScope handle_scope;
// Running script
// v8::Script::Run()
// End running script
});
}
// Calculation and control of the execution time
v8::Locker locker;
v8::HandleScope handle_scope;
while ( true )
{
// terminate thread after 10 seconds
if( ( (::GetTickCount() - start_tick) / 1000 ) > 10 )
// v8::v8::TerminateException( )
}
v8::Locker::StopPreemption();
}
根据这个V8 bug报告,StartPreemption()
目前是不可靠的。但是,您不需要它来实现脚本执行超时。这个程序演示了一种方法:
#include "v8.h"
#include "ppltasks.h"
void main(void)
{
auto isolate = v8::Isolate::New();
{
v8::Locker locker(isolate);
v8::Isolate::Scope isolateScope(isolate);
v8::HandleScope handleScope(isolate);
auto context = v8::Context::New();
{
v8::Context::Scope contextScope(context);
auto script = v8::Script::Compile(v8::String::New("while(true){}"));
// terminate script in 5 seconds
Concurrency::create_task([isolate]
{
Concurrency::wait(5000);
v8::V8::TerminateExecution(isolate);
});
// run script
script->Run();
}
context.Dispose();
}
isolate->Dispose();
}
这里的计时器实现显然是次优的,特定于Windows并发运行时,但这只是一个例子。好运!
相关文章:
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- C++ 如何在将新对象分配给另一个对象时创建新对象
- 从抽象类继承以创建另一个抽象类时,我应该重新声明所有虚函数吗?
- Zmq 上下文 - 我应该在新线程中创建另一个上下文吗?
- 如何在makefile中添加.c,.cc和.so文件以创建另一个.so
- 如何在Arduino中创建另一个类库的实例变量
- Object 创建另一个实例,而不是修改指向的实例
- "std::string + char"表达式会创建另一个 std::string 吗?
- 程序如何创建另一个可执行文件
- 从另一个类创建另一个特定类的优雅/高效的方法
- 在 VC++ MFC 中创建另一个鼠标光标
- 在qt中创建另一个网络线程
- 如何创建另一个类 struc 的向量?(C++11)
- 创建另一个对象时出现内存错误
- JNI - 创建另一个C++类的实例
- 类在同一内存位置创建另一个类的多个对象(C++)
- 我如何在v8中创建另一个线程
- 构造函数在必须创建另一个类的新对象时是如何工作的
- 给定抽象基类 X,如何创建另一个模板类 D,<T>其中 T 是从 X 派生的类的类型?
- 在对象中创建另一个对象时,对象的成员变量将被重写