Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to do multi-threaded coding in NodeJS?

Based on my understanding, only I/O in NodeJS is non-blocking. If we do, for example, lots of heavy math operations, other users cannot access to the server until it's done.

I was wondering if there is a non-blocking way to do heavy computation in NodeJS? Just curious.

like image 928
Xi 张熹 Avatar asked Oct 27 '11 01:10

Xi 张熹


People also ask

How many threads can node js handle?

Node. js has two types of threads: one Event Loop and k Workers.

Is NodeJs single thread or multi thread?

Node JS Platform does not follow Request/Response Multi-Threaded Stateless Model. It follows Single Threaded with Event Loop Model. Node JS Processing model mainly based on Javascript Event based model with Javascript callback mechanism.

Is NodeJs always single threaded?

No. NodeJs is not single threaded. The NodeJs event loop operates on a single thread yes, but the async blocking operations are delegated to separate worker threads. These threads notify the main thread when they are done processing.

Can we make js multithreaded?

JavaScript does not support multi-threading because the JavaScript interpreter in the browser is a single thread (AFAIK). Even Google Chrome will not let a single web page's JavaScript run concurrently because this would cause massive concurrency issues in existing web pages.


2 Answers

If you have long-running calculations that you want to do with Node, then you will need to start up a separate process to handle those calculations. Generally this would be done by creating some number of separate worker processes and passing the calculations off to them. By doing this, you keep the main Node event loop unblocked.

On the implementation side of things, you have two main options.

  1. The first being that you manually spin off child processes using Node's child-process API functions. This one is nice because your calculations wouldn't even have to be javascript. The child process running the calculations could even be C or something.
  2. Alternatively, the Web Worker specification, has several implementations available through NPM if you search for 'worker'. I can't speak to how well these work since I haven't used any, but they are probably the way to go.

Update

I'd go with option one now. The current child process APIs support sending messages and objects between processes easily in a worker-like way, so there is little reason to use a separate worker module.

like image 85
loganfsmyth Avatar answered Oct 11 '22 17:10

loganfsmyth


You can use Hook.io to run a separate node process for your heavy computation and communicate between the two. Hook.io is particularly useful because it has auto-healing meshes meaning that if one of your hooks (processes) crashes it can be restarted automatically.

like image 2
kbjr Avatar answered Oct 11 '22 19:10

kbjr