javascript - Nodejs(Google Chrome)中的事件循环使用什么逻辑流模型

标签 javascript node.js google-chrome v8

很长一段时间,我认为 Chrome 和 Node.js 中使用的事件循环实现(libuv?)使用线程。但后来我正在阅读 this article在 Java 中的轻量级线程上,声明如下:

...instead of creating threads for each concurrent task (and blocking tasks), a dedicated thread (called an event loop) looks through all the tasks that are assigned to threads in a non-reactive model, and processes each of them on the same CPU core.


和书Computer Systems. A Programmer’s Perspective在关于并发应用程序的章节中指出,现代操作系统提供了三种基本方法来构建
并发程序(实现逻辑流的 3 种方法):
  • Processes. With this approach, each logical control flow is a process that is scheduled and maintained by the kernel. Since processes have separate virtual address spaces, flows that want to communicate with each other must use some kind of explicit interprocess communication (IPC) mechanism.

  • I/O multiplexing. This is a form of concurrent programming where applications explicitly schedule their own logical flows in the context of a single process. Logical flows are modeled as state machines that the main program explicitly transitions from state to state as a result of data arriving on file descriptors. Since the program is a single process, all flows share the same address space.

  • Threads. Threads are logical flows that run in the context of a single process and are scheduled by the kernel. You can think of threads as a hybrid of the other two approaches, scheduled by the kernel like process flows and sharing the same virtual address space like I/O multiplexing flows.


所以现在我想知道事件循环是否属于 I/O multiplexing逻辑流并且不使用线程?

最佳答案

我与V8团队无关,但我会尝试回答这个问题。
首先,V8 本身与事件循环无关。 Node.js 使用 libuv 来实现事件循环以及操作系统特定 API(网络、FS 等)的抽象。事件循环本身在单个操作系统线程上运行,并且大多数网络操作都在基于该线程的 I/O 多路复用 API(epoll、kqueue 等)上执行。
但是 libuv 也有一个线程池来运行阻塞 I/O(例如 FS、DNS 查找)和 CPU 密集型操作(例如加密)。线程池通过内存队列与事件循环集成(通信)。当必须启动阻塞/CPU密集型任务时,它被放入队列中,稍后其中一个线程开始处理它。
因此,Node.js 使用多种方法来实现用户操作之间的并发:操作系统线程(顺便说一句,这包括 worker_threads 模块)、I/O 多路复用、多进程(使用 child_process 模块)。
V8 还为自己的目的使用了许多 OS 线程(例如 GC),但它不需要了解事件循环或为 OS 级 API 提供任何抽象。它的目标是执行给定的 JS 代码并提供可靠的嵌入 API,以便您可以使用它构建浏览器/运行时。

关于javascript - Nodejs(Google Chrome)中的事件循环使用什么逻辑流模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68176293/

相关文章:

html - Firefox 表格单元格宽度与 Chrome 完全不同

javascript - Adsense 错误 : "Blocked a frame with origin.."

javascript:从 GM 脚本调用嵌入式函数

node.js - REST 服务的管理

javascript - ". Redirecting to" express

javascript - 此代码阻止我的表单提交(仅在 Chrome 中,适用于 IE 和 Firefox)

javascript - 如何使用 xmlhttp.open HTML 特殊字符?

javascript - 在 setState() 触发之前,Amp-state 会被忽略

javascript - 在使用索引更新变量时,所有具有相同键但不同索引的对象也在 react js 中发生变化

javascript - where 子句上的意外标记 ' : '