Take the following code taken from the nodejs event loop documentation :
// timeout_vs_immediate.js
setTimeout(() => {
console.log('timeout');
}, 0);
setImmediate(() => {
console.log('immediate');
});
According to the documentation :
For example, if we run the following script which is not within an I/O
cycle (i.e. the main module), the order in which the two timers are
executed is non-deterministic, as it is bound by the performance of
the process.
Why is the above statement true ? Is it because the nodejs runtime actually employs more than one thread to pick out the callbacks that have to be executed.
What my intuition says: there are two threads that execute callbacks for setTimeout
and setImmediate
so when both of them are available this leads to a race condition, and thus the output will be non-deterministic.
Is it correct ? Or is there any other reason for which this is non-deterministic ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…