Search code examples
node.jsmultithreadingasynchronoussynchronousevent-loop

Why nodejs fs sync synchronous apis block the main thread (even loop) when it should be execute on the worker pool (default of nodejs)?


This is a theory question,

I previously thought that in nodejs expensive tasks like I/O, Network,... will be executed on a worker in worker pool, not the main node event loop, so it doesn't block the event loop.

I read some articles about it, e.g nodejs docs

But today i read an article that wrote:

"As async is definitely a better solution for such cases, it's the sync versions of the methods that have proper -Sync suffix. You should keep in mind that the use of sync methods is just highly not-recommended and, when used, will block the main thread from performing any other operations. Just use them with care (and only if you really have to)!"

So if it's true, why these synchronous tasks will block the main even loop when it should be execute on the worker pool?

Thanks


Solution

  • So if it's true, why these synchronous tasks will block the main even loop when it should be execute on the worker pool?

    Because the sync versions are specifically designed to block the main thread so it will WAIT for them to complete before returning. They are designed to be blocking APIs. That's what they're designed to do. If they didn't do that, they'd be non-blocking and asynchronous, not blocking and synchronous.

    The issue isn't what thread the actual work gets done on. The issue is that the sync versions are specifically designed to make the main thread wait until they are done. This is to simplify programming in certain situations where a blocking behavior is desired. For example, it's not uncommon to use some synchronous file I/O in the startup code for a server. For example, require() does blocking file I/O to load scripts.

    But, as you've seen in the article, you only want to use asynchronous file I/O once your server is up and running and handling requests.