且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

NodeJS 事件循环的确切处理是什么?

更新时间:2021-12-25 04:30:23

您可以将事件循环视为一个实际的循环,例如:

You can think of the Event Loop as an actual loop, something like:

let event_queue = [compiled_toplevel_code];
while (true) {
  if (event_queue.length === 0) {
    sleepUntilWokenUp();
  }
  if (event_queue.length > 0) {
    let callback = event_queue.shift();
    callback();
  }
}

其中 sleepUntilWokenUp() 是一个特殊的函数,它会挂起当前线程,直到另一个线程发送一些信号来唤醒它.异步操作(如文件系统或网络访问)由此类其他线程处理.当他们有一个回调准备好执行时,他们会将它排入队列,然后发送适当的唤醒信号.

where sleepUntilWokenUp() is a special function that suspends the current thread until another thread sends some signal to wake it up. Async operations (like file system or network access) are handled by such other threads. When they have a callback ready to execute, they will enqueue it and then send the appropriate wake-up signal.

您可以将 setImmediate(callback) 想象为实现为 event_queue.push(callback).

You can imagine setImmediate(callback) as being implemented as event_queue.push(callback).

传输控制"从事件循环到回调仅仅意味着调用回调;回归控制"到事件循环只是意味着回调函数返回.

"Transferring control" from the event loop to a callback simply means calling the callback; "returning control" to the event loop simply means that the callback function returns.

长时间运行的异步"任务总是分解成在主线程上运行的片段,安排一些要完成的工作(通常在另一个线程上),然后返回.一旦请求的任务在后台完成,它们相应的回调就会被排队.甚至同步"带有 await 的调用只是将函数分成两半的语法糖,这样前半部分会运行完成,而后半部分会在等待任务时推送到 event_queue已经完成.

Long-running "async" tasks always decompose into snippets that run on the main thread, schedule some work to be done (typically on another thread), then return. Once the requested task has been completed in the background, their corresponding callback is enqueued. Even "synchronous" calls with await are just syntactic sugar for splitting the function in two halves such that the first half runs to completion, and the second half is pushed onto the event_queue when the awaited task has completed.

现实中的完整情况稍微复杂一些(在 Node 文档中有详细描述),不同种类的事物有几个不同的队列,但以上描述了总体思路.

The full situation in reality is somewhat more complicated (and described in detail in the Node documentation) with a few different queues for different kinds of things, but the above describes the general idea.