Can a setImmediate() function scheduled in an I/O callback recalculate timeout for other I/O notifications?

萝らか妹 提交于 2021-02-11 12:12:43

问题


There is the poll stage of the Node js's event loop. Its aim is to blockingly wait for I/O notifications and then execute needed callbacks. A timeout time of the waiting is calculated before entering this stage. If there were operations scheduled through setImmediate than the timeout is set at 0, if timers took place than timeout is set with a view of them and if there are no such impediments the blocking would continue "forever".

What will happen if the timeout is initially set at "infinity" and an I/O callback schedules a function with setImmediate or setInterval? Would the timeout be recalculated immediately or only after the I/O queue got empty (in a next loop iteration)?

So if we wait for two launched asynchronous opearations with callbacks A and B and after receiving an I/O notification A is executed and it in turn schedules some C function with setImmediate what the function would execute first B or C?


回答1:


Note that for some of the more common asynchronous API with timer support (eg. the select() or kqueue() system call) a timer value of zero (0) represents the value of infinity so you cannot implement a function like setImmediate() or nextTick() the usual way by calculating the next timeout value and calling the asynchronous API. Instead all setImmediate() or nextTick() callbacks must be called synchronously before calling the asynchronous API.

Therefore, since C is a callback to setImmediate() it will be called before we re-enter the event loop to wait for B to fire.

So if A and only a gets triggered then the sequence of function calls would be: A and C.

But if A and B happens at the same time the sequence of function calls would be: A, B, C.

Note that I said A and C and not A, C, B because we didn't say B gets triggered. For all I know B will only get triggered 8 months from now or even never.

But if A gets triggered and 1 millisecond later B happens then the sequence of function calls would be: A, C, B


Is it possible for two events to happen in the same event loop? Generally yes. If it's network I/O it is unlikely because IP packets are serialized but it can still happen especially if you have a machine with multiple network cards. If it's graphical events like DOM updates then two things happening in the same event loop is quite common eg: both page resize and content reflow can happen at the same time especially with responsive CSS using media query where page resize can trigger content reflow.



来源:https://stackoverflow.com/questions/65869806/can-a-setimmediate-function-scheduled-in-an-i-o-callback-recalculate-timeout-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!