简体   繁体   English

Node.js中的单线程如何真正工作?

[英]How does the single thread in Node.js really work?

I am currently reading into how Node.js works behind the scenes in detail. 我目前正在详细研究Node.js在幕后的工作方式。 The question I have is about its single threaded architecture and the event loop. 我有一个关于它的单线程体系结构和事件循环的问题。 I am already familiar with most of it but one thing is confusing me. 我已经熟悉了其中的大部分内容,但是有一件事让我感到困惑。 An online instructor said that it is okay for a heavy synchronous function to be called if it is in the "top-level" code. 一位在线讲师说,如果在“顶层”代码中,可以调用一个繁重的同步函数。 I understand that it runs before the event loop even starts but doesn't it still block other users since its on the single thread? 我知道它在事件循环甚至开始之前就运行了,但是由于它在单线程上,它是否还阻止其他用户?

It is common to run synchronous operations as part of a server startup and this is perfectly OK. 在服务器启动过程中通常会运行同步操作,这完全可以。 In fact, if you were not to use synchronous operations in server startup, the startup code may be a ton more complicated. 实际上,如果您不打算在服务器启动中使用同步操作,则启动代码可能要复杂得多。

For example, the require() operation is synchronous and blocking. 例如, require()操作是同步和阻塞的。 So, yes it's perfectly OK to use synchronous code in the server startup portion of your code. 因此,是的,在代码的服务器启动部分中使用同步代码是完全可以的。

But, once your server has started, using synchronous I/O code such as fs.readFileSync() in any sort of request handler can ruin the scalability of your server. 但是,一旦服务器启动,在任何类型的请求处理程序中使用fs.readFileSync()类的同步I / O代码可能会破坏服务器的可伸缩性。

I understand that it runs before the event loop even starts but doesn't it still block other users since its on the single thread? 我知道它在事件循环甚至开始之前就运行了,但是由于它在单线程上,它是否还阻止其他用户?

If the synchronous code is before the server has started serving requests, then there are no other users yet to block. 如果同步代码在服务器开始服务请求之前,则没有其他用户要阻止。 It's just part of the code that gets the server going. 它只是使服务器运行的代码的一部分。

If the synchronous code is after the server has started serving requests, then yes it would block other requests from being processed while the synchronous code was running and that would be an undesirable thing because it would significantly reduce the scalability and responsiveness of your server. 如果同步代码是在服务器开始处理请求之后执行的,那么是的,它将阻止其他代码在运行同步代码时被处理,这将是不可取的事情,因为它将大大降低服务器的可伸缩性和响应能力。

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

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