我想为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();
  }

最佳答案

根据this V8 bug reportStartPreemption()目前不可靠。但是,您不需要它来实现脚本执行超时。该程序演示了一种方法:

#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 Concurrency Runtime,但这只是一个示例。祝好运!

关于c++ - 如何在v8中创建另一个线程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16516100/

10-13 06:31