【问题标题】:Calling a JS function by event emitting通过事件发射调用 JS 函数
【发布时间】:2014-08-12 02:06:07
【问题描述】:

我不确定如何通过在单独的 C++ 线程中使用事件发射来在 Node 的主线程中调用 Node/v8 函数。如何在 C++ 线程中发出事件?

在考虑 NanAsyncWorker 或 uv_queue_work 之前:我不想以异步方式调用 C++ 函数。我想做完全相反的事情,通过发出事件从 C++ 调用 Javascript 函数。

【问题讨论】:

  • Javascript 是一种单线程语言。这意味着如果您需要从另一个线程调用 javascript 中的函数,您将需要异步执行。还是我误会了?
  • @loganfsmyth 是的,这正是我的意图,在单独的线程中触发事件以在主线程中调用 JS 函数。

标签: c++ multithreading node.js node-modules


【解决方案1】:

您不需要使用uv_queue_work,但LibUV 的线程库的一部分是uv_async_* 方法,这是您在这种情况下最理想的方法。当你初始化你的辅助线程时,你还需要uv_async_init 来创建一个共享的async 数据结构。这个函数也被调用一个回调,只要你的其他线程发送消息就会运行。该回调是您调用 JS 代码来触发事件的地方。

这里有一些半伪代码作为例子:

在从 JS 调用的线程初始化函数中,使用单个回调 arg:

void ThreadInit(const v8::Arguments &args){
  // This is just an example, this should be saved somewhere that
  // some_callback will be able to access it.
  v8::Persistent<v8::Function> js_callback = args[0].As<Function>();

  // And save this where you'll be able to call uv_close on it.
  uv_async_t async_data;

  uv_async_init(uv_default_loop(), &async_data, some_callback);

  // initialize the thread and pass it async_data
}

在线程中:

async_data.data = (void*) // Some data structure...
uv_async_send(&async_data);

在线程回调中:

void some_callback(uv_async_t *async_data){
    // Note that this depending on the data, you could easily get thread-safety issues
    // here, so keep in mind that you should follow standard processes here.
    void* data = async_data->data;

    // Process that data however you need to in order to create a JS value, e.g.
    // Using NanNew because it is more readable than standard V8.
    v8::Local<Number> count = NanNew<Number>(data.count);

    v8::Local<v8::Value> argv[] = {
        count
    };

    js_callback->Call(NanNull(), 1, argv);
}

【讨论】:

  • 错误:从 'v8::Local<:function>' 转换为非标量类型 'v8::Persistent<:function>' 请求 v8::Persistent<:> js_callback = args[0].As();
  • 也许 V8 在过去两年发生了变化?不知道现在有没有别的办法,抱歉。
猜你喜欢
  • 2018-03-19
  • 1970-01-01
  • 1970-01-01
  • 2013-10-11
  • 2018-03-23
  • 2022-01-21
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
相关资源
最近更新 更多