Grasping the Node JS alternative to multithreading
Yes, I'd say that your understanding is entirely correct. This article (archived) explains the rationale behind this design quite well. This is probably the most important paragraph:
Apache is multithreaded: it spawns a thread per request (or process, it depends on the conf). You can see how that overhead eats up memory as the number of concurrent connections increases and more threads are needed to serve multiple simulataneous clients. Nginx and Node.js are not multithreaded, because threads and processes carry a heavy memory cost. They are single-threaded, but event-based. This eliminates the overhead created by thousands of threads/processes by handling many connections in a single thread.
Even if this is an old thread, I thought, that I would share with an idea, how to utilize more that one core in Node.JS app. As Nuray Altin have mentioned - JXcore can do that.
Simple example:
var method = function () {
console.log("this is message from thread no", process.threadId);
};
jxcore.tasks.runOnThread(0, method);
jxcore.tasks.runOnThread(1, method);
// this is message from thread no 1
// this is message from thread no 0
By default there are two threads (you can change it with jxcore.tasks.setThreadCount()
)
Of course there is much more that you can do with tasks. The docs are here.
Few articles on that subject:
- How multithreaded JXcore applications benefit from multiple cores.
- How to turn your existing application into a multithreaded one with a few lines of code!
Pretty much correct, yes. The node.js server has an internal thread pool so it can perform blocking operations and notify the main thread with a callback or event when things complete.
So I imagine that it will make limited use of another core for the thread pool, for example if you do a non-blocking file system read this is likely implemented by telling a thread from the thread pool to perform a read and set a callback when it's done which means that the read could be happening on a different thread/core while the main node.js program is doing something else.
But from a node.js point of view, it's entirely single threaded and won't directly use more than one core.