106

Is there any way to create threads for running multiple methods at a time?

That way, if any method fails in between all the other threads should be killed.

jkdev
  • 11,360
  • 15
  • 54
  • 77
user87267867
  • 1,409
  • 3
  • 18
  • 25

12 Answers12

106

New answer: While node.js didn't used to have the ability to use threading natively, the ability has since been added. See https://nodejs.org/api/worker_threads.html for details.

Old answer: Every node.js process is single threaded by design. Therefore to get multiple threads, you have to have multiple processes (As some other posters have pointed out, there are also libraries you can link to that will give you the ability to work with threads in Node, but no such capability exists without those libraries. See answer by Shawn Vincent referencing https://github.com/audreyt/node-webworker-threads)

You can start child processes from your main process as shown here in the node.js documentation: http://nodejs.org/api/child_process.html. The examples are pretty good on this page and are pretty straight forward.

Your parent process can then watch for the close event on any process it started and then could force close the other processes you started to achieve the type of one fail all stop strategy you are talking about.

Also see: Node.js on multi-core machines

Brian
  • 3,264
  • 4
  • 30
  • 43
  • processes can run parallel and sequential at a time? – user87267867 Sep 04 '13 at 12:09
  • 2
    The child processes are independent of the parent process. They have their own memory space, PID, and execution time. Not sure what you mean by sequential, but yes, they will run in parallel and be scheduled separately by the OS for execution. – Brian Sep 04 '13 at 12:13
  • how to call user defined functions as child process? – user87267867 Sep 04 '13 at 12:40
  • How can i spawn a child process to call function abc(){} – user87267867 Sep 04 '13 at 12:56
  • You have to put it in another .js file that has code that calls that function and then start that file executing with node with a command like so: var spawn = require('child_process').spawn, newProcess = spawn('node', ['abc.js']); – Brian Sep 04 '13 at 16:03
  • Putting in another .js file will act as parent which will call the child abc.js. Similarly if there are mutiple functions fun1(),fun2(),fun3() which has to run parallely and fun2() fails in between then it should kill fun1() and fun3() execution. – user87267867 Sep 04 '13 at 18:40
  • i have spawned many child var spawn = require('child_process').spawn,newProcess1 = spawn('node', ['File1.js']),newProcess2 = spawn('node', ['File2.js']),newProcess3 = spawn('node', ['File3.js']); which will run parallely.If newProcess1 fails then newProcess2 and newProcess3 must be stopped or killed. – user87267867 Sep 05 '13 at 06:20
  • hmmm I not a CS expert but I'd say if the OS can spawn both processes and threads, then Node can do both also. What about this? https://github.com/audreyt/node-webworker-threads – Alexander Mills Jan 05 '15 at 08:53
  • 2
    Huh, wasn't aware of that library but it does look like per Alex Mills comment you can do some threading work in Node. That being said, the next question is should you. . . Node was designed from ground up to free programmers from complexity that come with threads but yield similar type performance for blocking I/O. I will edit my answer to account for the fact that it is possible using the referenced library. – Brian Jan 08 '15 at 19:45
  • 1
    seems like this answer is out of date – danday74 Jan 19 '22 at 10:49
34

There is also at least one library for doing native threading from within Node.js: node-webworker-threads

https://github.com/audreyt/node-webworker-threads

This basically implements the Web Worker browser API for node.js.

Shawn Vincent
  • 501
  • 4
  • 3
25

Update 2:

Since Node.js 12 LTS Worker threads are stable.


Update 1:

From Node v11.7.0 onward, you do not have to use --experimental-worker flag.

Release note: https://nodejs.org/en/blog/release/v11.7.0/


From Node 10.5 there is now multi threading support, but it is experimental. Hope this will become stable soon.

Checkout following resources :

user158
  • 12,852
  • 7
  • 62
  • 94
10

You can get multi-threading using Napa.js.

https://github.com/Microsoft/napajs

"Napa.js is a multi-threaded JavaScript runtime built on V8, which was originally designed to develop highly iterative services with non-compromised performance in Bing. As it evolves, we find it useful to complement Node.js in CPU-bound tasks, with the capability of executing JavaScript in multiple V8 isolates and communicating between them. Napa.js is exposed as a Node.js module, while it can also be embedded in a host process without Node.js dependency."

shmuli
  • 5,086
  • 4
  • 32
  • 64
7

I needed real multithreading in Node.js and what worked for me was the threads package. It spawns another process having it's own Node.js message loop, so they don't block each other. The setup is easy and the documentation get's you up and running fast. Your main program and the workers can communicate in both ways and worker "threads" can be killed if needed.

Since multithreading and Node.js is a complicated and widely discussed topic it was quite difficult to find a package that works for my specific requirement. For the record these did not work for me:

  • tiny-worker allowed spawning workers, but they seemed to share the same message loop (but it might be I did something wrong - threads had more documentation giving me confidence it really used multiple processes, so I kept going until it worked)
  • webworker-threads didn't allow require-ing modules in workers which I needed

And for those asking why I needed real multi-threading: For an application involving the Raspberry Pi and interrupts. One thread is handling those interrupts and another takes care of storing the data (and more).

Heinrich Ulbricht
  • 10,064
  • 4
  • 54
  • 85
5

The nodejs 10.5.0 release has announced multithreading in Node.js. The feature is still experimental. There is a new worker_threads module available now.

You can start using worker threads if you run Node.js v10.5.0 or higher, but this is an experimental API. It is not available by default: you need to enable it by using  --experimental-worker when invoking Node.js.

Here is an example with ES6 and worker_threads enabled, tested on version 12.3.1

//package.json

  "scripts": {
  "start": "node  --experimental-modules --experimental- worker index.mjs"
  },

Now, you need to import Worker from worker_threads. Note: You need to declare you js files with '.mjs' extension for ES6 support.

//index.mjs
import { Worker } from 'worker_threads';

const spawnWorker = workerData => {
    return new Promise((resolve, reject) => {
        const worker = new Worker('./workerService.mjs', { workerData });
        worker.on('message', resolve);
        worker.on('error', reject);
        worker.on('exit', code => code !== 0 && reject(new Error(`Worker stopped with 
        exit code ${code}`)));
    })
}

const spawnWorkers = () => {
    for (let t = 1; t <= 5; t++)
        spawnWorker('Hello').then(data => console.log(data));
}

spawnWorkers();

Finally, we create a workerService.mjs

//workerService.mjs
import { workerData, parentPort, threadId } from 'worker_threads';

// You can do any cpu intensive tasks here, in a synchronous way
// without blocking the "main thread"
parentPort.postMessage(`${workerData} from worker ${threadId}`);

Output:

npm run start

Hello from worker 4
Hello from worker 3
Hello from worker 1
Hello from worker 2
Hello from worker 5
Priyesh Diukar
  • 2,032
  • 1
  • 15
  • 19
4

If you're using Rx, it's rather simple to plugin in rxjs-cluster to split work into parallel execution. (disclaimer: I'm the author)

https://www.npmjs.com/package/rxjs-cluster

Jonathan Dunlap
  • 2,581
  • 3
  • 19
  • 22
2

There is also now https://github.com/xk/node-threads-a-gogo, though I'm not sure about project status.

shaunc
  • 5,317
  • 4
  • 43
  • 58
2

NodeJS now includes threads (as an experimental feature at time of answering).

James Holmes
  • 394
  • 2
  • 5
0

You might be looking for Promise.race (native I/O racing solution, not threads)

Assuming you (or others searching this question) want to race threads to avoid failure and avoid the cost of I/O operations, this is a simple and native way to accomplish it (which does not use threads). Node is designed to be single threaded (look up the event loop), so avoid using threads if possible. If my assumption is correct, I recommend you use Promise.race with setTimeout (example in link). With this strategy, you would race a list of promises which each try some I/O operation and reject the promise if there is an error (otherwise timeout). The Promise.race statement continues after the first resolution/rejection, which seems to be what you want. Hope this helps someone!

smileham
  • 1,430
  • 2
  • 16
  • 28
  • 2
    This has nothing to do with threads. They all run in the same thread. – Evan Carroll Apr 23 '17 at 00:51
  • @EvanCarroll - Thank you for alerting me that I wasn't clear enough. I prefaced it with an assumption about why someone might be looking up thread racing and noted that this uses promises in Node's event loop. Coming from another language, it's very possible you want to accomplish what threads do but aren't familiar with the event loop or promises yet. I wanted to note that there are simpler ways to accomplish that if that's your goal. I added a parenthetical that this does not use threads. Let me know if this clears things up. – smileham Apr 24 '17 at 02:44
  • It also seems to answer the OPs criteria: "If any method fails in between all the other threads should be killed", so I figured it was relevant. – smileham Apr 24 '17 at 02:46
  • Promise.race executes all the promises sequentially, switching from one to other in case of an asynchronous operation (or await in case of an async function). – Nagabhushan Baddi May 26 '20 at 12:48
0

Node.js doesn't use threading. According to its inventor that's a key feature. At the time of its invention, threads were slow, problematic, and difficult. Node.js was created as the result of an investigation into an efficient single-core alternative. Most Node.js enthusiasts still cite ye olde argument as if threads haven't been improved over the past 50 years.

As you know, Node.js is used to run JavaScript. The JavaScript language has also developed over the years. It now has ways of using multiple cores - i.e. what Threads do. So, via advancements in JavaScript, you can do some multi-core multi-tasking in your applications. user158 points out that Node.js is playing with it a bit. I don't know anything about that. But why wait for Node.js to approve of what JavaScript has to offer.

Google for JavaScript multi-threading instead of Node.js multi-threading. You'll find out about Web Workers, Promises, and other things.

Roger F. Gay
  • 1,830
  • 2
  • 20
  • 25
0

You can't run multiple threads natively in node.js, however if you really need to offload some code from the main thread, you can always use child_process fork() to run some code in another process with it's own PID and memory.

Lennon McLean
  • 308
  • 3
  • 12