nodejs / node-addon-examples

Node.js C++ addon examples from http://nodejs.org/docs/latest/api/addons.html
Other
2.5k stars 600 forks source link

When using functions from addon blocks the main process node js? #77

Open saper639 opened 5 years ago

saper639 commented 5 years ago

Implemented a wrapper for the function using N-API. It works, but the problem is that when it works the main thread of the node does not work? How can I rewrite this function so that it does not block the main thread? What do I need to use async, callback, thread for this?

napi_value readDataSerial(napi_env env, napi_callback_info info) {
        napi_status status;
        size_t argc = 1;    
        napi_value args[1], object;  
        napi_value id, data;
        status = napi_get_cb_info(env, info, &argc, args, NULL, NULL);
        assert(status == napi_ok);
        if (argc < 1) {
          napi_throw_type_error(env, NULL, "Wrong number of arguments");
          return NULL;
        }    
        //....
        Ibox_ReadData *context = calloc(1, sizeof(Ibox_Context));
        //this function takes a long time and blocks the main process
        Ibox_Result_Submit *submitResult = Ibox_Controller_ReadData(context);
        status = napi_create_object(env, &object);
        status = napi_create_string_utf8(env, submitResult->id, NAPI_AUTO_LENGTH, &id);
        status = napi_set_named_property(env, object, "id", id);         
        status = napi_create_string_utf8(env, submitResult->date, NAPI_AUTO_LENGTH, &date);
        status = napi_set_named_property(env, object, "data", data);         
        assert(status == napi_ok);
        return object;
    })  
mhdawson commented 5 years ago

You should read up on https://nodejs.org/api/n-api.html#n_api_simple_asynchronous_operations