为什么Node.js是单线程的?\[关闭\]

node.js Node.js

蛋蛋猿

2020-03-20

在基于PHP(或Java / ASP.NET / Ruby)的Web服务器中,每个客户端请求都在新线程上实例化。但是在Node.js中,所有客户端都在同一线程上运行(它们甚至可以共享相同的变量!)我知道I / O操作是基于事件的,因此它们不会阻塞主线程循环。

我不明白为什么Node的作者选择了它为单线程?这使事情变得困难。例如,我无法运行CPU密集型功能,因为它阻塞了主线程(并且阻塞了新的客户端请求),因此我需要产生一个进程(这意味着我需要创建一个单独的JavaScript文件并在其上执行另一个节点进程)它)。但是,在PHP cpu中,密集型任务不会阻止其他客户端,因为正如我提到的那样,每个客户端都在不同的线程上。与多线程Web服务器相比,它的优势是什么?

注意:我已经使用集群解决了这个问题,但这并不是很漂亮。

第2496篇《为什么Node.js是单线程的?\[关闭\]》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
宝儿LEY理查德 2020.03.20

Node.js是作为异步处理中的实验而显式创建的。从理论上讲,在典型的Web负载下,与典型的基于线程的实现相比,在单个线程上执行异步处理可以提供更高的性能和可伸缩性。

你知道吗?我认为理论已经被证实。与Apache或IIS或其他基于线程的服务器相比,不占用大量CPU资源的node.js应用程序可以运行数千个并发连接。

单线程异步性质的确使事情变得复杂。但是,老实说,您认为它比线程处理还要复杂吗?一种比赛条件可能会破坏您的整个月!或者由于某处的某些设置而清空线程池,并观察响应时间变慢以进行爬网!更不用说死锁,优先级倒置以及与多线程相关的所有其他回旋。

最后,我不认为它普遍好坏。这是不同的,有时更好,有时则不是。使用正确的工具完成工作。

TomTom乐 2020.03.20

总而言之,节点来自内部单线程的V8。有一些方法可以解决CPU密集型任务的约束。

在某一时刻(0.7),作者试图引入隔离来实现多个计算线程,但最终被删除:https : //groups.google.com/forum/#!msg/ nodejs/zLzuo292hX0/ F7gqfUiKi2sJ

神无 2020.03.20

服务器的“每个请求一个线程”模型的问题在于,与事件循环线程模型相比,它们在几种情况下无法很好地扩展。

通常,在I / O密集型方案中,请求花费大部分时间等待I / O完成。在此期间,在“每个请求一个线程”模型中,链接到该线程的资源(例如内存)未使用,内存是限制因素。在事件循环模型中,循环线程选择下一个要处理的事件(I / O完成)。因此,线程总是很忙(如果正确编程的话)。

The event loop model as all new things seems shiny and the solution for all issues but which model to use will depend on the scenario you need to tackle. If you have an intensive I/O scenario (like a proxy), the event base model will rule, whereas a CPU intensive scenario with a low number of concurrent processes will work best with the thread-based model.

In the real world most of the scenarios will be a bit in the middle. You will need to balance the real need for scalability with the development complexity to find the correct architecture (e.g. have an event base front-end that delegates to the backend for the CPU intensive tasks. The front end will use little resources waiting for the task result.) As with any distributed system it requires some effort to make it work.

If you are looking for the silver bullet that will fit with any scenario without any effort, you will end up with a bullet in your foot.

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android