javascriptc++electronnode.js-addonn-api

N-API C++ addon causing Electron GUI to block


I have an N-API C++ addon that I would like to use with an Electron GUI. Currently the C++ addon has a simple function that sleeps for 10 seconds and then performs a computation of 8*2, and returns the value to the Javascript code. The Javascript code runs the C++ addon every 10 seconds.

// 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();

However, when I run the above code I find that the native C++ addon causes the Electron GUI to block for 10 seconds, each time it runs. Is there any way that I can perform my heavy computation in the background and have the Electron GUI not block or freeze? I assume I would have to use some sort of threads but I'm not sure how to do it with N-API. Below are the rest of my files including the module.cpp and the package.json file.

// 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"
  }
}

Solution

  • The reason it blocks Electron is the sleep(10). That call doesn't return for 10 seconds.

    So yes, there is a way to offload heavy computation to another thread. The biggest complication from doing so is that the thread can't make a callback to JavaScript without taking extra precautions nor can the thread access JavaScript data structures, so it must be provided with all the data necessary.

    Here's the example the C++ abstraction provides for N-API using a thread to calculate Pi.

    node-addon-example

    And here are C++ wrappers to create thread-safe callbacks.

    napi-threadsafe-callback

    It's not trivial but these two examples should get you through it.