简体   繁体   English

Nodejs中的单个线程是什么意思

[英]What does it mean by single thread in Nodejs

I often hear Node runs in only one thread. 我经常听到Node只在一个线程中运行。 However, the thing I don't understand is how node can do non-blocking with only one thread. 但是,我不明白的是节点如何只用一个线程进行非阻塞。 Let's say there are 100 concurrent requests coming to a node web server, the server generates 100 callbacks to handle the requests. 假设有100个并发请求进入节点Web服务器,服务器生成100个回调来处理请求。 If each of the 100 callbacks takes 1 second to complete, and if all of them are in 1 thread, they have to be done in series, does it mean it will block for 100 seconds? 如果100个回调中的每一个都需要1秒才能完成,并且如果所有这些回调都在1个线程中,那么它们必须连续完成,是否意味着它会阻塞100秒?

From the blog Understanding the node.js event loop 从博客了解node.js事件循环

The largest waste with current programming technologies comes from waiting for I/O to complete.There are several ways in which one can deal with the performance impact (from Sam Rushing): 使用当前编程技术的最大浪费来自等待I / O完成。有几种方法可以处理性能影响(来自Sam Rushing):

  • synchronous: you handle one request at a time, each in turn. 同步:您一次处理一个请求,每个请求依次处理。 pros: simple cons: any one request can hold up all the other requests 优点:简单的缺点:任何一个请求都可以阻止所有其他请求
  • fork a new process: you start a new process to handle each request. fork一个新进程:启动一个新进程来处理每个请求。 pros: easy cons: does not scale well, hundreds of connections means hundreds of processes. 优点:简单的缺点:不能很好地扩展,数百个连接意味着数百个进程。 fork() is the Unix programmer's hammer. fork()是Unix程序员的锤子。 Because it's available, every problem looks like a nail. 因为它可用,所以每个问题看起来都像钉子一样。 It's usually overkill 这通常是矫枉过正的

  • threads: start a new thread to handle each request. 线程:启动一个新线程来处理每个请求。 pros: easy, and kinder to the kernel than using fork, since threads usually have much less overhead cons: your machine may not have threads, and threaded programming can get very complicated very fast, with worries about controlling access to shared resources. 优点:比使用fork更容易,更耐用于内核,因为线程通常具有更少的开销缺点:您的机器可能没有线程,并且线程编程可能非常快速地变得非常复杂,担心控制对共享资源的访问。

Node.js keeps a single thread for your code… Node.js为你的代码保留一个线程......

It really is a single thread running: you can't do any parallel code execution; 它实际上是一个单线程运行:你不能执行任何并行代码执行; doing a “sleep” for example will block the server for one second: 例如,进行“休眠”将阻止服务器一秒钟:

while(new Date().getTime() < now + 1000) {
   // do nothing
}

So while that code is running, node.js will not respond to any other requests from clients, since it only has one thread for executing your code. 因此,当该代码运行时,node.js不会响应来自客户端的任何其他请求,因为它只有一个线程来执行您的代码。 Or if you would have some CPU -intensive code, say, for resizing images, that would still block all other requests. 或者,如果您有一些CPU密集型代码,比如说,用于调整图像大小,那么仍会阻止所有其他请求。

Read more 阅读更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM