Search code examples
node.jsasynchronousiolibuv

Why does node spawn several threads?


I listed the threads of my node server and following was the response on stdout:

$ ps -e -T | grep 14209
14209 14209 ?        00:10:08 node
14209 14415 ?        00:00:00 V8 WorkerThread
14209 14416 ?        00:00:00 V8 WorkerThread
14209 14417 ?        00:00:00 V8 WorkerThread
14209 14418 ?        00:00:00 V8 WorkerThread
14209 14419 ?        00:00:00 node
14209 15894 ?        00:00:00 node
14209 15895 ?        00:00:00 node
14209 15896 ?        00:00:00 node
14209 15902 ?        00:00:00 node

I've learnt that nodejs is single threaded and the same thread is responsible for handling javascript code. So, what is the purpose of last five threads? Are they spawned by libuv which handles asynchronous I/O?


Solution

  • So, what is the purpose of last five threads? Are they spawned by libuv which handles asynchronous I/O?

    At least some of them (if not all of them) are due to libuv, yes.
    The library has a thread pool (it's explicitly mentioned in the documentation) used mainly for fs requests, even though not only for them:

    libuv provides a threadpool which can be used to run user code and get notified in the loop thread. This thread pool is internally used to run all file system operations, as well as getaddrinfo and getnameinfo requests.

    That's because things like fs requests are intrinsically synchronous and the sole way to make them seem asynchronous is to spawn the requests on separate threads and then treat the responses on the main thread.

    That being said, it's true that the JavaScript environment is single threaded, but it doesn't force the underlying libraries (mainly v8 and libuv) not to use threads internally for their purposes. As long as the JavaScript runtime appears to the user as single threaded, there is no reason not to use threads.
    Actually that's exactly what those libraries do at some extent to perform their tasks and improve performance: they spawn threads and use them internally.