node.js/libuv 如何使用反应器模式支持异步 io

How does node.js/libuv support async io using the reactor pattern

libuv 用于处理 IO 的反应器模式在设计上是同步的,但 libuv 支持异步 io。这怎么可能? libuv 是否以某种方式扩展反应器的设计以支持异步 io?使用多个 threads/event 循环是否有助于实现此目的?

Node 和 libuv 的 I/O 模型与 nginx 内部所做的非常相似。

libuv 使用单线程事件循环和非阻塞异步I/O。所有函数都以它们 运行 完成的方式同步,但是一些带有承诺和生成器的聪明黑客可以用来显示它们没有(实际上生成器函数的调用是非阻塞的并且 returns 立即生成器对象和生成器方法,如 .next() 运行 完成),加上新的 async/await 语法使其非常方便。

对于无法以非阻塞方式完成的操作,Node 使用线程池来 运行 单独线程中的阻塞操作,但这是透明完成的,并且永远不会暴露给编写的应用程序代码JavaScript(您需要降级到 C++ 才能直接使用它)。

参见:http://docs.libuv.org/en/v1.x/design.html

Unlike network I/O, there are no platform-specific file I/O primitives libuv could rely on, so the current approach is to run blocking file I/O operations in a thread pool. [...]

libuv currently uses a global thread pool on which all loops can queue work on. 3 types of operations are currently run on this pool:

  • File system operations
  • DNS functions (getaddrinfo and getnameinfo)
  • User specified code via uv_queue_work()

有关更多详细信息,另请参阅这些答案:

  • what is mean by event loop in node.js ? javascript event loop or libuv event loop? *NodeJS event loop internal working
  • Prevent NodeJS from exiting event-loop
  • How node.js server serve next request, if current request have huge computation?
  • Which would be better for concurrent tasks on node.js? Fibers? Web-workers? or Threads?
  • Speed up setInterval
  • Async.js - Is parallel really parallel?

查看这些答案中的链接和插图。有很多资源可以阅读有关该主题的内容。