简体   繁体   English

为什么response.write会阻塞线程?

[英]why does response.write block the thread?

Here's the example below: 这是下面的示例:

 const http = require('http') const server = http.createServer() const log = console.log.bind(console) server.on('request', (req, res) => { log('visited!') res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', }) for (let i = 0; i < 100000; i++) { res.write('<p>hello</p>') } res.end('ok') }) server.listen(3000, '0.0.0.0') 

When the server is handling the first request, the thread is blocked and can't handle the second request. 当服务器处理第一个请求时,该线程被阻止,无法处理第二个请求。 I wonder why would this happen since nodejs uses an event-driven, non-blocking I/O model. 我不知道为什么会发生这种情况,因为nodejs使用了事件驱动的非阻塞I / O模型。

Great question. 好问题。

NodeJS uses a non-blocking I/O model; NodeJS使用非阻塞I / O模型; that is, I/O operations will run on separate threads under the hood, but all JavaScript code will run on the same event-loop driven thread. 也就是说,I / O操作将在幕后的不同线程上运行,但是所有JavaScript代码将在同一事件循环驱动的线程上运行。

In your example, when you ask your HTTP server to listen for incoming requests, Node will manage the socket listening operations on a separate thread under the hood so that your code can continue to run after calling server.listen() . 在您的示例中,当您请求HTTP服务器侦听传入的请求时,Node将在幕后的另一个线程上管理套接字侦听操作,以便您的代码可以在调用server.listen()之后继续运行。

When a request comes, your server.on('request') callback is executed back on the main event-loop thread. 当请求到来时,您的server.on('request')回调将在主事件循环线程上执行。 If another request comes in, its callback cannot run until the first callback and any other code that is currently executing on the main thread finishes. 如果另一个请求进入,则其回调将无法运行,直到第一个回调和当前在主线程上执行的任何其他代码完成。

Most of the time, callbacks are short-lived so you rarely need to worry about blocking the main thread. 在大多数情况下,回调是短暂的,因此您几乎不必担心阻塞主线程。 If the callbacks aren't short-lived, they are almost always calling an asynchronous I/O related function that actually does run in a different thread under the hood, therefore freeing up the main thread for other code to execute. 如果回调不是短暂的,则它们几乎总是调用与异步I / O相关的函数,该函数实际上在后台运行在另一个线程中,因此释放了主线程供其他代码执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM