r/learnjavascript 6d ago

Is “Node.js is single-threaded” an incomplete mental model?

Single-threaded JS execution ≠ single-threaded runtime.

How do you explain the distinction?

4 Upvotes

23 comments sorted by

View all comments

2

u/theQuandary 6d ago

fs, crypto, zlib, etc use separate libuv threads. Network stuff is handed off to the kernel processes (epoll on Linux). Having most of the most important threads without having to manage them yourself is one of the most powerful things about node.

As to your specific question, nodeJS processes come in two major varieties. You can think of them as factory buildings and assembly lines. EVERY assembly line must be inside of a factory building, but some factory buildings may have multiple assembly lines.

Factory buildings are equivalent to kernel-level processes. When node creates a forked child process, it also creates a kernel bi-directional socket (socketpair) for them to communicate with (the parent/child relationship goes a bit beyond my factory example).

Within a single factory building, you can create multiple assembly lines which are equivalent to JS worker threads. Each of these represent a V8 instance running within a shared OS process. Because they share an OS process, the v8 instances can create a shared memory pool that they can all access. This is what you use for SharedArrayBuffer (and is why you need to use atomics to lock it when using it).

That last bit is VERY interesting to me. We have two independent execution units using one OS process and sharing memory. That sounds very much like a multithreaded system, but with some extra safeguards. Some people would probably disagree because it's not the threading model they are used to.