简体   繁体   中英

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

I am currently reading into how Node.js works behind the scenes in detail. 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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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