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?
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):
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With