Node.js如何处理一个线程的同时请求? [英] How does Node.js handle simultaneous requests with one thread?

查看:69
本文介绍了Node.js如何处理一个线程的同时请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此问题进行了一些搜索,但似乎人们只强调非阻塞IO.

I did some search on the question, but it seems like people only emphasize on Non-blocking IO.

让我们说如果我只有一个非常简单的应用程序来向客户端响应"Hello World"文本,那么不管它有多快,它仍然需要时间来完成执行.如果有两个请求完全同时出现,该怎么办?Node.js如何确保两个请求都用一个线程处理?

Let's say if I just have a very simple application to respond "Hello World" text to the client, it still needs time to finish the execution, no matter how quick it is. What if there are two request coming in at exactly the same time, how does Node.js make sure both requests will be processed with one thread?

我阅读了博客了解节点.js事件循环表示当然,在后端,存在用于数据库访问和过程执行的线程和过程".该语句与IO有关,但我也想知道是否有单独的线程来处理请求队列.如果是这样,我可以说Node.js单线程概念仅适用于在Node.js上构建应用程序的开发人员,但是Node.js实际上是在幕后的多线程上运行的吗?

I read the blog Understanding the node.js event loop which says "Of course, on the backend, there are threads and processes for DB access and process execution". That statement is regarding IO, but I also wonder if there is separate thread to handle the request queue. If that's the case, can I say that the Node.js single thread concept only applies to the developers who build applications on Node.js, but Node.js is actually running on multi-threads behind the scene?

推荐答案

操作系统为每个套接字连接分配一个发送和接收队列.这就是字节所在的位置,直到应用程序层的某些内容处理它们为止.如果接收队列已满,则在队列中没有可用空间之前,所有已连接的客户端都无法发送信息.这就是应用程序应尽可能快地处理请求的原因.

The operating system gives each socket connection a send and receive queue. That is where the bytes sit until something at the application layer handles them. If the receive queue fills up no connected client can send information until there is space available in the queue. This is why an application should handle requests as fast as possible.

如果您使用的是* nix系统,则可以使用netstat查看发送和接收队列中的当前字节数.在此示例中,接收队列中有0个字节,发送队列中有240个字节(等待操作系统发送出去).

If you are on a *nix system you can use netstat to view the current number of bytes in the send and receive queues. In this example, there are 0 bytes in the receive queue and 240 bytes in the send queue (waiting to be sent out by the OS).

Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      240 x.x.x.x:22                 x.x.x.x:*                   LISTEN

在Linux上,您可以使用proc文件系统检查发送/接收队列的默认大小和允许的最大大小:

On Linux you can check the default size and max allowed size of the send/receive queues with the proc file system:

Receive:

cat /proc/sys/net/core/rmem_default
cat /proc/sys/net/core/rmem_max

Send:

cat /proc/sys/net/core/wmem_max
cat /proc/sys/net/core/wmem_default

这篇关于Node.js如何处理一个线程的同时请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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