我正在使用 C++ 插件编写nbind - GitHub 链接 https://github.com/charto/nbind对于大多数事情和Nan - GitHub 链接 https://github.com/nodejs/nan/用于异步调用回调。当我只调用一次回调时,它工作得很好。但是当我调用回调两次时它给出Segmentation fault (core dumped)
。使用时找不到错误gdb
。这是JS和C++代码(使用编译node-gyp configure build
):
//main.js code
var nbind = require('nbind');
var lib = nbind.init().lib;
lib.HeaderExample.callJS(function(a) {
console.log("result" + a);
});
lib.HeaderExample.startThread();
lib.HeaderExample.startThread();
C++ 插件的代码
//c++ code
class CallbackRunner : public Nan::AsyncWorker {
public:
CallbackRunner(Nan::Callback *callback)
: AsyncWorker(callback) {}
void Execute () {}
void HandleOKCallback () {
std::cout << "running HandleOKCallback in thread " << std::this_thread::get_id() << std::endl;
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = {
Nan::New<v8::Number>(10)
};
callback->Call(1, argv);
}
};
class HeaderExample {
public:
static void callJS(nbind::cbFunction &callback) {
std::cout << "running callJS in thread " << std::this_thread::get_id() << std::endl;
m_onInitialisationStarted = new nbind::cbFunction(callback);
Nan::Callback *callbackNan = new Nan::Callback(m_onInitialisationStarted->getJsFunction());
runner = new CallbackRunner(callbackNan);
}
static void startThread() {
std::cout << "it is here";
std::thread threadS(some);
threadS.join();
}
static void some() {
std::cout << "running some in thread: " << std::this_thread::get_id() << std::endl;
if(runner){
AsyncQueueWorker(runner);
}
}
inline static nbind::cbFunction *m_onInitialisationStarted = 0;
inline static CallbackRunner *runner;
};
你的班级使用AsyncQueueWorker
调用CallbackRunner
, but AsyncQueueWorker
calls AsyncExecuteComplete
回调完成后,依次调用worker->Destroy()
。请参阅AsyncQueueWorker
代码来自nan.h
:
inline void AsyncExecute (uv_work_t* req) {
AsyncWorker *worker = static_cast<AsyncWorker*>(req->data);
worker->Execute();
}
inline void AsyncExecuteComplete (uv_work_t* req) {
AsyncWorker* worker = static_cast<AsyncWorker*>(req->data);
worker->WorkComplete();
worker->Destroy();
}
inline void AsyncQueueWorker (AsyncWorker* worker) {
uv_queue_work(
uv_default_loop()
, &worker->request
, AsyncExecute
, reinterpret_cast<uv_after_work_cb>(AsyncExecuteComplete)
);
}
worker->Destroy()
将删除CallbackRunner
类,以及Nan::Callback
您将其提供给其构造函数。这就是为什么在尝试第二次调用此回调时出现分段错误的原因。
你可能最好将你的课程基于Nan::AsyncProgressQueueWorker
代替Nan::AsyncWorker
. AsyncProgressQueueWorker
继承AsyncWorker
它允许您从主线程安排工作,就像AsyncWorker
确实如此,但它为您提供了ExecutionProgress
该类允许您在原始计划作业运行时使用任何线程任意次数地回调主线程。
Nan::AsyncProgressQueueWorker
被添加到NAN在版本中2.8.0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)