Question

I knows that when doing I/O operations, nodejs does the work in a separate thread, so, can't the thread run in the other core? if so, isn't that only one nodejs process can make use of two cores?

Was it helpful?

Solution

Node does asynchronous I/O but the I/O is very little "work" in terms of CPU. It's mostly waiting for the OS to have data ready to be processed. So a single node process is only going to make good use of 1 CPU core for the actual logic in your node program itself. If you max out that CPU core and want more of your actual program's logic to run at the same time, you need another process. Yes, there are technically a handful of threads in use by any node program, but only 1 of them is the CPU-intensive one that is actually interpreting your javascript.

It's mostly waiting for the OS to have data ready to be processed. So a single node process is only going to make good use of 1 CPU core for the actual logic in your node program itself. why?

This is by design. By making this particular choice, node programs do not have to deal with complex and error-prone concurrent programming idioms such as threads, semaphores, locking, deadlocks, etc. It's just one choice of dealing with that complexity. It is based on two main observations that 1. asynchronous I/O seems to be currently regarded as the most efficient and manageable design for high-concurrency systems and 2. Most of the other programming idioms for concurrency are relatively more difficult to code correctly. This is just what node.js chose. The "go" language, for example, made a different set of choices favoring other idioms that allow multithreading, blocking, channels, message queueing, etc. Consequently, go programs make better use of multi-core machines.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top