如何在nodejs中创建线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18613023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create threads in nodejs
提问by user87267867
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.
这样,如果任何方法在所有其他线程之间失败,都应该被杀死。
回答by Brian
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)
每个 node.js 进程都是单线程设计的。因此,要获得多个线程,您必须有多个进程(正如其他一些海报指出的那样,您还可以链接到一些库,这将使您能够在 Node 中使用线程,但是如果没有这些库,就不存在这种功能. 参见 Shawn Vincent 参考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.
您可以从主进程启动子进程,如 node.js 文档中所示:http: //nodejs.org/api/child_process.html。此页面上的示例非常好,而且非常简单。
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
另请参阅: 多核机器上的 Node.js
回答by Shawn Vincent
There is also at least one library for doing native threading from within Node.js: node-webworker-threads
还有至少一个库用于在 Node.js 中进行本地线程处理:node-webworker-threads
https://github.com/audreyt/node-webworker-threads
https://github.com/audreyt/node-webworker-threads
This basically implements the Web Worker browser APIfor node.js.
这基本上实现了node.js的Web Worker 浏览器 API。
回答by user158
From Node 10.5 there is now multi threading support, but it is experimental. Hope this will become stable soon.
从 Node 10.5 现在有多线程支持,但它是实验性的。希望这会很快稳定下来。
Checkout following resources :
结帐以下资源:
- 公关线。
- 官方文档
- 博客文章:Node 10.5.0 中的线程:实用介绍
Update:
更新:
From Node v11.7.0onward, you do not have to use --experimental-workerflag.
从 Node v11.7.0开始,您不必使用--experimental-worker标志。
Release note: https://nodejs.org/en/blog/release/v11.7.0/
回答by shmuli
You can get multi-threading using Napa.js.
您可以使用 Napa.js 获得多线程。
https://github.com/Microsoft/napajs
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."
“Napa.js 是一个基于 V8 的多线程 JavaScript 运行时,最初设计用于在 Bing 中开发具有不妥协性能的高度迭代服务。随着它的发展,我们发现在 CPU 密集型任务中补充 Node.js 很有用,具有在多个 V8 隔离中执行 JavaScript 并在它们之间进行通信的能力。Napa.js 作为 Node.js 模块公开,同时它也可以嵌入到没有 Node.js 依赖的主机进程中。”
回答by Jonathan Dunlap
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)
如果您正在使用 Rx,那么在 rxjs-cluster 中插入插件以将工作拆分为并行执行是相当简单的。(免责声明:我是作者)
回答by Heinrich Ulbricht
I needed realmultithreading in Node.js and what worked for mewas the threadspackage. 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.
我需要在 Node.js 中使用真正的多线程,而对我有用的是线程包。它产生了另一个拥有自己的 Node.js 消息循环的进程,因此它们不会相互阻塞。设置很简单,文档可以让您快速启动和运行。您的主程序和工作人员可以通过两种方式进行通信,如果需要,工作人员“线程”可以被终止。
Since multithreading and Node.js is a complicated and widely discussed topic it was quite difficult to find a package that works for myspecific requirement. For the record these did not work for me:
由于多线程和 Node.js 是一个复杂且被广泛讨论的话题,因此很难找到适合我的特定需求的包。根据记录,这些对我不起作用:
- tiny-workerallowed spawning workers, but they seemed to share the same message loop (but it might be I did something wrong - threadshad more documentation giving me confidence it reallyused multiple processes, so I kept going until it worked)
- webworker-threadsdidn't allow
require-ing modules in workers which I needed
- tiny-worker允许产生工人,但他们似乎共享相同的消息循环(但可能是我做错了什么 -线程有更多的文档让我相信它确实使用了多个进程,所以我一直继续直到它工作)
- webworker-threads不允许
require在我需要的工作线程中使用-ing 模块
And for those asking why I needed realmulti-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).
对于那些问我为什么需要真正的多线程的人:对于涉及 Raspberry Pi 和中断的应用程序。一个线程处理这些中断,另一个线程负责存储数据(以及更多)。
回答by Frostbyte1010
The nodejs 10.5.0 release has announced multithreading in Node.js. The feature is still experimental. There is a new worker_threadsmodule available now.
nodejs 10.5.0 版本宣布了 Node.js 中的多线程。该功能仍处于试验阶段。现在有一个新的worker_threads模块可用。
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-workerwhen invoking Node.js.
如果您运行Node.js v10.5.0 或更高版本,则可以开始使用工作线程,但这是一个实验性 API。默认情况下不可用:您需要通过使用启用它吗?--experimental-worker调用 Node.js 时。
Here is an example with ES6and worker_threadsenabled, tested on version 12.3.1
这是启用了ES6和worker_threads的示例,在 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 jsfiles with '.mjs' extensionfor ES6 support.
现在,您需要从worker_threads导入 Worker 。注意:您需要使用“.mjs”扩展名声明js文件以支持 ES6。
//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
//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
npm 运行开始
Hello from worker 4
Hello from worker 3
Hello from worker 1
Hello from worker 2
Hello from worker 5
回答by James Holmes
回答by shaunc
There is also now https://github.com/xk/node-threads-a-gogo, though I'm not sure about project status.
现在还有https://github.com/xk/node-threads-a-gogo,虽然我不确定项目状态。
回答by smileham
You might be looking for Promise.race(native I/O racing solution, not threads)
您可能正在寻找Promise.race(本机 I/O 竞赛解决方案,而不是线程)
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.racewith 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.racestatement continues after the first resolution/rejection, which seems to be what you want. Hope this helps someone!
假设您(或其他搜索此问题的人)想要竞争线程以避免失败并避免 I/O 操作的成本,这是一种简单且原生的方式来完成它(不使用线程)。Node 被设计为单线程的(查看事件循环),所以尽可能避免使用线程。如果我的假设是正确的,我建议您使用Promise.racewith setTimeout(链接中的示例)。使用此策略,您将竞争一个承诺列表,每个承诺尝试一些 I/O 操作并在出现错误时拒绝承诺(否则超时)。该Promise.race声明在第一个决议/拒绝之后继续,这似乎是您想要的。希望这可以帮助某人!

