How to create threads in nodejs

user87267867 picture user87267867 · Sep 4, 2013 · Viewed 139.1k times · Source

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.

Answer

Brian picture Brian · Sep 4, 2013

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