I have setup this repo which executes a node-addon-api thread safe function in a SWIG C++ class.
The thread in the SWIG C++ class is executed using the napi BlockingCallback like so :
// inside C++ thread
for (int i=0; i<4){
sleep(1);
int* value = new int( clock() );
napi_status status = tsfn->BlockingCall( value, callback );
if ( status != napi_ok ) { // Handle error }
}
// thread exits at this point
When I execute the javascript, the thread safe function is not executed until the thread has exited where the following code :
// setup the ThreadSafeFunction to call from the thread
let fp = libNapiNodejs.start(function () {
console.log("JavaScript callback called with arguments", Array.from(arguments));
}, 5);
test.run(); // run the C++ thread in the SWIG module
// in the main thread, print out main every second
const id = setInterval(()=>console.log('main'),1000);
test.meetThread(); // wait for the C++ thread to exit
// the thread's queued function calls are executed now that the thread has exited
This is what is printed out when I run ./test/RunTest.js :
C++ Thread enter threadMain
thread loop 0 of 4
calling tsfn->BlockingCall
thread loop 1 of 4
calling tsfn->BlockingCall
thread loop 2 of 4
calling tsfn->BlockingCall
thread loop 3 of 4
calling tsfn->BlockingCall
C++ Thread exit threadMain
main
JavaScript callback called with arguments [ 48084 ]
JavaScript callback called with arguments [ 48218 ]
JavaScript callback called with arguments [ 48287 ]
JavaScript callback called with arguments [ 48356 ]