libuv 用于处理 IO 的 react 器模式在设计上是同步的,但 libuv 支持异步 io。这怎么可能? libuv 是否以某种方式扩展了 react 器的设计以支持异步 io?使用多个线程/事件循环有助于实现这一目标吗?
最佳答案
Node 和 libuv 的 I/O 模型与 nginx 内部的操作非常相似。
libuv 使用单线程事件循环和非阻塞异步 I/O。所有函数都是同步的,它们运行到完成,但可以使用一些带有 Promise 和生成器的聪明黑客来显示它们不是同步的(事实上,生成器函数的调用都是非阻塞的并返回生成器对象)立即和生成器方法(如 .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?
- Node.js: Asynchronous Callback Execution. Is this Zalgo?
请参阅这些答案中的链接和插图。有很多关于该主题的资源可供阅读。
关于node.js - Node.js/libuv 如何使用 react 器模式支持异步 io,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45212770/