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

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

问题描述

在基于 PHP(或 Java/ASP.NET/Ruby)的网络服务器中,每个客户端请求都在一个新线程上实例化.但是在 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天全站免登陆