您可能需要一些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
当您的 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);
}