我们如何阻止事件循环?

Dig*_*ore 8 event-loop node.js

我研究了 Node.Js 中的事件循环,它以异步和非阻塞的方式工作来处理请求。有什么办法可以阻止事件循环的执行吗?

jfr*_*d00 18

有很多方法可以阻止事件循环。有些方法只是暂时阻止它(例如使用同步文件 I/O),而有些方法则永远阻止它。

例如,这将永远阻止它:

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
Run Code Online (Sandbox Code Playgroud)

问题是while()循环一直运行直到flag值发生变化。只要 while 循环正在运行,事件循环就会被阻塞。有一个setTimeout()想要在 1 秒内触发的函数,但在解释器返回到事件循环之前它实际上无法调用其回调。while()但是,在循环完成之前它不会返回到事件循环。这是一个死锁,会导致无限循环并且事件循环被永久阻塞。

在循环完成之前,无法调用其回调,并且在setTimeout()运行其回调之前,循环不会完成。死锁,无限循环。whilewhilesetTimeout()


当所有文件操作和所有文件处理正在进行时,这会阻止它一段时间:

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("\n");
    for (let line of lines) {
        // do something
    }
}
Run Code Online (Sandbox Code Playgroud)