我在 NodeJS 中使用 bcrypt 来生成密码哈希。 Bcrypt 文档说我们可以使用 genSalt()、compare() 和 hash() 函数的异步版本。
NodeJS 是单线程的,所以理论上,如果我使用 CPU 绑定(bind)代码,即使使用异步等待也会阻塞线程。如果我在这种情况下使用异步等待函数,我的应用程序会发生什么变化? CPU 绑定(bind)代码在什么情况下会受益于使用异步等待模式?
最佳答案
Node.js 是单线程的,因为它的主要事件循环 在单个线程上运行,但这并不意味着它不能在其标准 API 中使用工作线程来处理事情比如 I/O 和密码学(两者都在不同的线程上工作)。
为了编写第 3 方库,例如 bcrypt
等,我们能够为 Node.js 编写 C++ 附加组件,利用提供的线程池通过 libuv ,支持 Node.js 中事件循环的库。并引入Node.js Worker Threads在 v10.5 中,我们可以编写多线程程序,而无需编写任何 C++。
查看 bcrypt
的文档,他们提到他们使用线程池来避免阻塞主循环:
If you are using bcrypt on a simple script, using the sync mode is perfectly fine. However, if you are using bcrypt on a server, the async mode is recommended. This is because the hashing done by bcrypt is CPU intensive, so the sync version will block the event loop and prevent your application from servicing any other inbound requests or events. The async version uses a thread pool which does not block the main event loop.
关于node.js - 为什么在 Node.js CPU 绑定(bind)代码中使用异步模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54565157/