我有一个想与 Electron GUI 一起使用的 N-API C++ 插件。目前 C++ 插件有一个简单的函数,它会休眠 10 秒,然后执行 8*2 的计算,并将值返回给 Javascript 代码。Javascript 代码每 10 秒运行一次 C++ 插件。
// index.js
const addon = require('./build/Release/module');
const electron = require('electron');
const {app, BrowserWindow} = require('electron');
let win;
function createWindow() {
win = new BrowserWindow({width: 800, height: 600});
win.loadFile('./index.html');
win.on('closed', () => {win = null});
}
app.on('ready', createWindow);
app.on('activate', () => {
if (win === null) {
createWindow();
}
})
function getInfoFromNativeModule() {
const value = 8;
console.log(`${value} times 2 equals`, addon.my_function(value));
setTimeout(getInfoFromNativeModule, 1000);
}
getInfoFromNativeModule();
但是,当我运行上述代码时,我发现本机 C++ 插件每次运行时都会导致 Electron GUI 阻塞 10 秒。有什么方法可以让我在后台执行繁重的计算并使 Electron GUI 不会阻塞或冻结?我假设我必须使用某种线程,但我不确定如何使用 N-API 来做到这一点。下面是我的其余文件,包括 module.cpp 和 package.json 文件。
// module.cpp
napi_value MyFunction(napi_env env, napi_callback_info info) {
napi_status status;
size_t argc = 1;
int number = 0;
napi_value argv[1];
status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL);
if (status != napi_ok) {
napi_throw_error(env, NULL, "Failed to parse arguments");
}
status = napi_get_value_int32(env, argv[0], &number);
if (status != napi_ok) {
napi_throw_error(env, NULL, "Invalid number was passed as argument");
}
napi_value myNumber;
number = number * 2;
std::cout << "sleeping for 10 seconds" << std::endl;
sleep(10);
std::cout << "waking up" << std::endl;
status = napi_create_int32(env, number, &myNumber);
if (status != napi_ok) {
napi_throw_error(env, NULL, "Unable to create return value");
}
return myNumber;
}
napi_value Init(napi_env env, napi_value exports) {
napi_status status;
napi_value fn;
status = napi_create_function(env, NULL, 0, MyFunction, NULL, &fn);
if (status != napi_ok) {
napi_throw_error(env, NULL, "Unable to wrap native function");
}
status = napi_set_named_property(env, exports, "my_function", fn);
if (status != napi_ok) {
napi_throw_error(env, NULL, "Unable to populate exports");
}
return exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
// package.json
{
"name": "n-api-article",
"version": "0.1.0",
"main": "index.js",
"scripts": {
"start": "node-gyp rebuild && electron .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/schahriar/n-api-article.git"
},
"engines": {
"node": ">=8.4.0"
},
"dependencies": {
"electron": "^4.0.8",
"electron-rebuild": "^1.8.4"
}
}