Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean by single thread in Nodejs

I often hear Node runs in only one thread. 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. 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?

like image 505
Qian Chen Avatar asked Nov 26 '13 17:11

Qian Chen


1 Answers

From the blog Understanding the node.js event loop

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):

  • 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. pros: easy cons: does not scale well, hundreds of connections means hundreds of processes. fork() is the Unix programmer’s hammer. 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.

Node.js keeps a single thread for your code…

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. Or if you would have some CPU -intensive code, say, for resizing images, that would still block all other requests.

Read more

like image 92
Damodaran Avatar answered Oct 19 '22 16:10

Damodaran