简体   繁体   English

有什么简单的方法可以在 node.js 中运行并行 for 循环吗?

[英]Is there any simple way to run a parallel for loop in node.js?

Coming from C#, I use the Parallel library.来自 C#,我使用并行库。 an example for a parallel for loop in c# would be: c# 中的并行 for 循环示例如下:

Parallel.ForEach(sourceCollection, item => Process(item));

In node.js i couldn't find anything simillar.在 node.js 我找不到任何类似的东西。 I know the worker-threads library, but isn't there any simpler way to run a loop without implementing a thread pool behind the scenes?我知道工作线程库,但是没有更简单的方法来运行循环而不在幕后实现线程池吗?

Node.js does not have any built-in mechanism for running a synchronous loop in parallel. Node.js 没有任何用于并行运行同步循环的内置机制。 You would have to find a module that can already do that or manually create your own iterator that fired up a workerThread for each invocation of the loop (or used a pool of threads) and then communicate back the results from the workerThread.您必须找到一个已经可以做到这一点的模块,或者手动创建您自己的迭代器,该迭代器为循环的每次调用(或使用线程池)启动一个 workerThread,然后从 workerThread 传回结果。

If I were implementing your loop and needed to run multiple synchronous Process(item) operations in parallel, I would probably create a work queue and a pool of workers servicing the queue and I'd put a promise returning wrapper around Process() .如果我正在实现您的循环并需要并行运行多个同步Process(item)操作,我可能会创建一个工作队列和一个为队列服务的工作人员池,并且我会在Process()周围放置一个 promise 返回包装器。 Inside that wrapper, it would add it to the workQueue, register a callback with the queue for completion and then when it completes resolve the promise it returned.在该包装器中,它会将其添加到工作队列中,向队列注册一个回调以完成,然后在完成时解析它返回的 promise。 You would then use Promise.all() to collect all the results in order.然后,您将使用Promise.all()按顺序收集所有结果。 Inside the workQueue, you'd have a set of workers grabbing an item from the queue, running it in a separate thread, then communicating back the result, then grabbing the next item and so on.在 workQueue 中,您将有一组工作人员从队列中抓取一个项目,在单独的线程中运行它,然后将结果传回,然后抓取下一个项目,依此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM