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

                    Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                    Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                    2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived