为什么Node.js是单线程的? [英] Why is Node.js single threaded?

查看:175
本文介绍了为什么Node.js是单线程的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In PHP (or Java/ASP.NET/Ruby) based webservers every client request is instantiated on a new thread. But in Node.js all the clients run on the same thread (they can even share the same variables!) I understand that I/O operations are event-based so they don't block the main thread loop.

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

What I don't understand is WHY the author of Node chose it to be single-threaded? It makes things difficult. For example, I can't run a CPU intensive function because it blocks the main thread (and new client requests are blocked) so I need to spawn a process (which means I need to create a separate JavaScript file and execute another node process on it). However, in PHP cpu intensive tasks do not block other clients because as I mentioned each client is on a different thread. What are its advantages compared to multi-threaded web servers?

注意:我已经使用聚类解决了这个问题,但这并不漂亮.

Note: I've used clustering to get around this, but it's not pretty.

推荐答案

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

Node.js was created explicitly as an experiment in async processing. The theory was that doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.

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

And you know what? In my opinion that theory's been borne out. A node.js app that isn't doing CPU intensive stuff can run thousands more concurrent connections than Apache or IIS or other thread-based servers.

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

The single threaded, async nature does make things complicated. But do you honestly think it's more complicated than threading? One race condition can ruin your entire month! Or empty out your thread pool due to some setting somewhere and watch your response time slow to a crawl! Not to mention deadlocks, priority inversions, and all the other gyrations that go with multithreading.

最后,我认为这并不普遍好或坏.这是不同的,有时更好,有时却没有.使用正确的工具完成工作.

In the end, I don't think it's universally better or worse; it's different, and sometimes it's better and sometimes it's not. Use the right tool for the job.

这篇关于为什么Node.js是单线程的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆