Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

node.js - How can we block event loop?

I have studied about the event loop in Node.Js, it work in asynchronous and non-blocking manner to process the request. Is there any way so that we can block the execution of event loop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are lots of ways to block the event loop. Some ways block it just for awhile (like using synchronous file I/O) and some ways block it forever.

For example, this blocks it forever:

let flag = false;
setTimeout(() => {
    // this callback never gets called
    // because event loop is blocked
    flag = true;
}, 1000);

while (!flag) {
    console.log("still waiting")
}
// never get here

The issue is that the while() loop runs until the flag changes value. As long as that while loop is running, the event loop is blocked. There's a setTimeout() that wants to fire in 1 second, but it can't actually call its callback until the interpreter gets back to the event loop. But, it won't get back to the event loop until the while() loop is done. It's a deadlock which results in an infinite loop and the event loop is permanently blocked.

The setTimeout() can't call its callback until the while loop is done and the while loop won't finish until the setTimeout() runs its callback. Deadlock, infinite loop.


This blocks it for awhile while all the file operations are going on and all the processing of the files:

setTimeout(() => {
    // this doesn't get to run until all the synchronous file I/O 
    // finishes in the code below, even though the timer is set
    // for only 10ms
    console.log("finally got to run the timer callback");
}, 10);

let files = some array of files;
for (let file of files) {
    let data = fs.readFileSync(file);
    let lines = data.split("
");
    for (let line of lines) {
        // do something
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...