Closed necil closed 5 years ago
@necil You didn't post what the secondary thread actually does, but I assume it calls the thread-safe function several times, or even in a loop.
The fact that you see "test" after both loops are done is the expected behaviour for the code you show, because sleep()
does not mean "suspend execution of JavaScript thereby giving Node.js a chance to check the event loop". It means "prevent the main thread from running for 200 ms". This also prevents Node.js from examining the event loop. So, although you have sleep()
in your loop, it's still a "busy" loop in the sense that it does not allow examination of the event loop while the loop is executing.
You can get interleaving if you replace the busy loops with idle loops:
global.AddTwo = function (num) {
process.stdout.write('\r\033[Ktest ' + num + '\r');
};
register();
new Promise((resolve) => {
let i = 0;
const interval = setInterval(() => {
console.log('\033[Kpass1');
i++;
if (i == 10) {
clearInterval(interval);
resolve();
}
}, 200);
})
.then(() => {
return new Promise((resolve) => {
let i = 0;
const interval = setInterval(() => {
console.log('\033[Kpass2');
i++;
if (i == 10) {
clearInterval(interval);
resolve();
}
}, 200);
});
});
I added some escape sequences to the output formatting because if you have the secondary thread run in a busy loop the words "test
Thank you i will try it
Tried and it works as it should. Thanks a lot. By the way I know my code was lacking some details, its because some parts of the code contains business logic and not possible for me to post that part online. Sorry for inconvenience.
@necil no problem. Glad you got it sorted out 🙂
Hello I am currently using N-API on node v11.12.0
I have two threads on addon side. first thread is my main thread and second one contains a loop that calls a function with specific interval.
I create thread safe function as follows (part of register() function):
Also callback function:
nodejs code:
I see the log test. However it happens after other two for loops completes. By the way interval of this call is much less than these for loop times. Therefore I expect to see a mixed logs of
pass1
orpass2
andtest
. As I mentioned above it starts to work through the loops after both loops finished it starts to printtest
as it triggers from native code. Since it passes both loops I am not suspecting that I do not block event loop completely(thats why I use to second loop). It seems like i am making a mistake and my callback only runs at when threadsafe function's destructor is reached. Am I missing anything or this is the expected behavior of this functionality?