I have been reading nodejs lately, trying to understand how it handles multiple concurrent requests, I know nodejs is a single threaded event loop based architecture, at a given point of time only one statement is gonna execute i.e, on main thread and blocking code/IO calls are handled by the worker threads (default is 4).
Now my question is what happens when a web server built using nodejs receives multiple requests, I know, there are a lots of Stack overflow thread that has similar questions, but didn't find a concrete answer to this.
So I am putting an example here, let's say we have following code inside a route like /index.
app.use('/index', function(req, res, next) { console.log("hello index routes was invoked"); readImage("path", function(err, content) { status = "Success"; if(err) { console.log("err :", err); status = "Error" } else { console.log("Image read"); } return res.send({ status: status }); }); var a = 4, b = 5; console.log("sum =", a + b); });
Let's assume that readImage() takes around 1 min to read that Image, so If two request T1, and T2 came concurently How nodejs is gonna process this ?
Does it going to take first request T1, process it while queueing the request T2 (please correct me if my understanding is wrong here), if any async/blocking stuff is encountered like readImage, it then sends that to worker thread (some point later when async stuff is done it notifies the main thread and main thread starts executing the callback), move ahead by executing the next line of code. When it is done with T1 then picks T2 request ? Is it correct? or it can process T2 code in between (meaning while readImage is called, it can start processing T2)?
I would really appreciate your help if anyone can answer this question.
from How does node process concurrent requests?
No comments:
Post a Comment