gpt4 book ai didi

c++ - 如何从插件中的单独 C++ 线程调用发射器回调?

转载 作者:行者123 更新时间:2023-12-03 01:30:53 25 4
gpt4 key购买 nike

对于上下文,我从 this 开始问题。我需要在另一个线程中调用发射器的回调。我做了一个最小的例子,但它在 emit.Call({cb, result}); 上出现段错误,我的第一直觉是我对 env发出函数。

addon.cpp

#include <napi.h>
#include <iostream>
#include <thread>
#include <memory>
#include <functional>
#include <chrono>

std::shared_ptr<std::thread> thread;
bool running = true;

void generate(Napi::Env& env, Napi::Function& emit)
{
while(running)
{
Napi::Array result = Napi::Array::New(env);

for(int i = 0; i < 3; ++i)
{
result[i] = rand()%100;
}

auto cb = Napi::String::New(env, "onFeedData");

emit.Call({cb, result});

std::this_thread::sleep_for(std::chrono::seconds(1));
}
}

Napi::Value Start(const Napi::CallbackInfo& info)
{
Napi::Env env = info.Env();
Napi::Function emit = info[0].As<Napi::Function>();

auto cb = std::bind(generate, env, emit);
thread = std::make_shared<std::thread>(cb);

return Napi::String::New(env, "OK");
}

Napi::Value Stop(const Napi::CallbackInfo& info)
{
Napi::Env env = info.Env();
Napi::Function emit = info[0].As<Napi::Function>();

running = false;
thread->join();

return Napi::String::New(env, "OK");
}

Napi::Object Init(Napi::Env env, Napi::Object exports)
{
exports.Set(
Napi::String::New(env, "Start"),
Napi::Function::New(env, Start));

exports.Set(Napi::String::New(env, "Stop"),
Napi::Function::New(env, Stop));

return exports;
}

NODE_API_MODULE(addon, Init)

index.js

'use strict'

const EventEmitter = require('events').EventEmitter;
const addon = require('./build/addon.node');

function Main() {
const emitter = new EventEmitter();

emitter.on('onFeedData', (evt) => {
console.log(evt);
})

setTimeout(() => {
addon.Stop( emitter.emit.bind(emitter) );
}, 5000);

addon.Start( emitter.emit.bind(emitter) );
}

Main();

最佳答案

我们可以通过利用napi_create_threadsafe_function()函数来实现这一点; StackOverflow 帖子 How to use napi_threadsafe_function for NodeJS Native Addon 详细解释了这种用法。

这是Asynchronous Thread-safe Function Calls的node.js文档

关于c++ - 如何从插件中的单独 C++ 线程调用发射器回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55714406/

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