N-API C++ addon causing Electron GUI to blockIs there a C++ gdb GUI for Linux?Incorrect result after serializing and deserializing time_t variableWhat is Linux’s native GUI API?Calling Node Native Addons (C++) in ElectronElectron crashes with C++ addon using openssl libraryNode Addons (C++) in ElectronAngular / Electron using the renderer.js with angular componentsProblem requiring native c++ addon from electronError while building c++ addon, whats the solution for it?

Languages that we cannot (dis)prove to be Context-Free

Can a vampire attack twice with their claws using Multiattack?

What is the word for reserving something for yourself before others do?

Was any UN Security Council vote triple-vetoed?

Is it inappropriate for a student to attend their mentor's dissertation defense?

Does an object always see its latest internal state irrespective of thread?

Do infinite dimensional systems make sense?

Why "Having chlorophyll without photosynthesis is actually very dangerous" and "like living with a bomb"?

Java Casting: Java 11 throws LambdaConversionException while 1.8 does not

Is it unprofessional to ask if a job posting on GlassDoor is real?

Replacing matching entries in one column of a file by another column from a different file

Client team has low performances and low technical skills: we always fix their work and now they stop collaborate with us. How to solve?

Perform and show arithmetic with LuaLaTeX

Is it legal for company to use my work email to pretend I still work there?

Why can't we play rap on piano?

Can I ask the recruiters in my resume to put the reason why I am rejected?

Watching something be written to a file live with tail

Why can't I see bouncing of a switch on an oscilloscope?

Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?

How can bays and straits be determined in a procedurally generated map?

meaning of に in 本当に?

Alternative to sending password over mail?

What does the "remote control" for a QF-4 look like?

What is a clear way to write a bar that has an extra beat?



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


Is there a C++ gdb GUI for Linux?Incorrect result after serializing and deserializing time_t variableWhat is Linux’s native GUI API?Calling Node Native Addons (C++) in ElectronElectron crashes with C++ addon using openssl libraryNode Addons (C++) in ElectronAngular / Electron using the renderer.js with angular componentsProblem requiring native c++ addon from electronError while building c++ addon, whats the solution for it?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















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"











share|improve this question




























    0















    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"











    share|improve this question
























      0












      0








      0








      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"











      share|improve this question














      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"








      javascript c++ electron node.js-addon n-api






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 9 at 1:02









      Raees RajwaniRaees Rajwani

      332313




      332313






















          1 Answer
          1






          active

          oldest

          votes


















          1














          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.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55072982%2fn-api-c-addon-causing-electron-gui-to-block%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            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.






            share|improve this answer



























              1














              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.






              share|improve this answer

























                1












                1








                1







                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.






                share|improve this answer













                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.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 12 at 11:40









                bmacnaughtonbmacnaughton

                2,77211728




                2,77211728





























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid …


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55072982%2fn-api-c-addon-causing-electron-gui-to-block%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                    Can't find variable: document ReactNative Js2019 Community Moderator ElectionReactNative: how to center text?Can't find variable: navigate - ReactNative navigationReact Native error: “Can't find variable: TouchableHighlight”How to use Expo.DocumentPicker.getDocumentAsync properly. [Expo] [ReactNative]Can't find variable: regeneratorRuntime (ReactNative)Reactnative Expo It is advisable for a StartUp?Can't find variable : Self / Can't install firebaseNPM Install Error in installing ReactNative CLIContacts Displaying in App using ReactnativeFacebook login error: can't find variable: Alert

                    Posting a File and Associated Data to a RESTful WebService preferably as JSON2019 Community Moderator ElectionREST URI convention - Singular or plural name of resource while creating itUploading both data and files in one form using Ajax?How do I upload a file with metadata using a REST web service?REST API - file (ie images) processing - best practicesSpring: JSON data and file in the same requestREST API Put large dataPosting a file and JSON data to Spring rest serviceRESTful Web Service Upload/Download Large Data With JSONREST API Design sending JSON data and a file to the api in same requestPost JSONArray to REST servicePUT vs. POST in RESTParsing values from a JSON file?JavaScript/jQuery to download file via POST with JSON dataHow do I upload a file with metadata using a REST web service?How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?Separate REST JSON API server and client?what's the correct way to send a file from REST web service to client?How do I write JSON data to a file?What is “406-Not Acceptable Response” in HTTP?REST API - file (ie images) processing - best practices