您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

V8多线程功能

V8多线程功能

您可能需要一些libuv魔术才能使node.js / v8 线程从 一个 线程执行回调。这将涉及:

一个uv_async_t句柄,它充当v8主线程的唤醒调用

extern uv_async_t       async;

一个uv_async_init结合了uv_async_t到V8认循环调用

uv_async_init(uv_default_loop(), &async, async_cb_handler);

还有一个事件处理程序,它将对 v8主线程 上的uvasync_t事件起作用:

void async_cb_handler(uv_async_t *handle) {
NotifInfo *notif;
mutex::scoped_lock sl(zqueue_mutex);
while (!zqueue.empty()) {
    notif = zqueue.front();
    handleNotification(notif);
    delete notif;
    zqueue.pop();
}

}

最后,您可能还需要一个互斥锁保护的队列,以便能够将某些数据从c ++附加线程传递到Node / V8:

extern mutex                   zqueue_mutex;

extern std::queue zqueue;

当您的 C ++线程 发生问题时,只需将新项目推送到互斥锁保护的队列中,然后调用uv_async_send即可唤醒V8的认事件循环(所谓的“主线程”)以处理该项目(然后可以调用您的Javascript回调)

void ozw_watcher_callback(OpenZWave::Notification const *cb, void *ctx) {
NotifInfo *notif = new NotifInfo();
notif->type   = cb->GetType();
notif->homeid = cb->GetHomeId();
...
mutex::scoped_lock sl(zqueue_mutex);
zqueue.push(notif);
uv_async_send(&async);

}

代码片段摘自用于OpenZWave的官方Node.JS插件

其他 2022/1/1 18:20:59 有539人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶