官术网_书友最值得收藏!

Event loop ordering, phases, and priorities

The event loop proceeds through phases, and each phase has a queue of events to process. From the Node documentation:

The phases relevant to developers are the following:

  • Timers: Callbacks deferred to some time in the future specified in milliseconds, such as setTimeout and setInterval
  • I/O callbacks: Prepared callbacks returned to the main thread after being delegated to Node's managed thread pool, such as filesystem calls and network listeners
  • Poll/checkMainly the functions slotted on the stack according to the rules of setImmediate and nextTick

When data becomes available on a socket or other stream interface, we cannot simply execute our callback immediately. JavaScript is single-threaded, so results must be synchronized. We can't suddenly change the state in the middle of an event loop tick — this would create some of the classic multithreaded application problems of race conditions, memory access conflicts, and so on.

To learn more about how Node is bound to libuv and other core libraries, parse through the fs module code at: https://github.com/nodejs/node/blob/master/lib/fs.js. Compare the fs.read and the fs.readSync methods to observe the difference between how synchronous and asynchronous actions are implemented; note the wrapper callback that is passed to the native binding.read method in fs.read. To take an even deeper pe into the very heart of Node's design, including the queue implementation, read through the Node source at: https://github.com/joyent/node/tree/master/src. Follow FSEventWrap within fs_event_wrap.cc. Investigate the req_wrap class, a wrapper for the V8 engine, deployed in node_file.cc and elsewhere and defined in req_wrap.h.

Upon entering an event loop, Node, in effect, makes a copy of the current instruction queue (also known as stack), empties the original queue, and executes its copy. The processing of this instruction queue is referred to as a tick. If libuv, asynchronously, receives results while the chain of instructions copied at the start of this tick are being processed on the single main thread (V8), these results (wrapped as callbacks) are queued. Once the current queue is emptied and its last instruction has completed, the queue is again checked for instructions to execute on the next tick. This pattern of checking and executing the queue will repeat (loop) until the queue is emptied, and no further data events are expected, at which point the Node process exits.

Next, let's look at the event interfaces of Node.

主站蜘蛛池模板: 金华市| 喀喇沁旗| 永顺县| 青铜峡市| 靖远县| 略阳县| 贵定县| 漳平市| 濮阳县| 山西省| 五常市| 屯留县| 历史| 台南市| 临夏市| 济南市| 昭通市| 乌兰浩特市| 溧水县| 县级市| 五常市| 广东省| 尼玛县| 宝应县| 札达县| 乐山市| 都兰县| 崇明县| 龙南县| 织金县| 临城县| 荥阳市| 泸水县| 盘山县| 茶陵县| 万山特区| 安龙县| 夏河县| 开江县| 玛曲县| 鄂托克旗|