How does node process concurrent requests?

前端 未结 6 725
你的背包
你的背包 2020-12-14 02:10

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 g

6条回答
  •  失恋的感觉
    2020-12-14 02:59

    For each incoming request, node will handle it one by one. That means there must be order, just like the queue, first in first serve. When node starts processing request, all synchronous code will execute, and asynchronous will pass to work thread, so node can start to process the next request. When the asynchrous part is done, it will go back to main thread and keep going.

    So when your synchronous code takes too long, you block the main thread, node won't be able to handle other request, it's easy to test.

    app.use('/index', function(req, res, next) {
        // synchronous part
        console.log("hello index routes was invoked");
        var sum = 0;
        // useless heavy task to keep running and block the main thread
        for (var i = 0; i < 100000000000000000; i++) {
            sum += i;
        }
        // asynchronous part, pass to work thread
        readImage("path", function(err, content) {
            // when work thread finishes, add this to the end of the event loop and wait to be processed by main thread
            status = "Success";
            if(err) {
                console.log("err :", err);
                status = "Error"
            }
            else {
                console.log("Image read");
            }
            return res.send({ status: status });
        });
        // continue synchronous part at the same time.
        var a = 4, b = 5;
        console.log("sum =", a + b);
    });
    

    Node won't start processing the next request until finish all synchronous part. So people said don't block the main thread.

提交回复
热议问题