gpt4 book ai didi

c++ - 调用某些回调函数两次导致段错误 : Nan

转载 作者:搜寻专家 更新时间:2023-10-31 01:31:34 25 4
gpt4 key购买 nike

我正在使用 nbind - GitHub link 编写 C++ 插件对于大多数事情和Nan - GitHub link用于异步调用回调。当我只调用一次回调时,它工作得很好。但是,当我两次调用回调时,它给出了 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,但是 AsyncQueueWorker 在回调完成后调用 AsyncExecuteComplete,依次调用 worker->Destroy()。请参阅 nan.h 中的 AsyncQueueWorker 代码:

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

关于c++ - 调用某些回调函数两次导致段错误 : Nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45589254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com