如何在Delphi中实现并行循环? [英] How to realize parallel loop in Delphi?

查看:226
本文介绍了如何在Delphi中实现并行循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Delphi中实现并行循环(Delphi 200X,Delphi XE)?怎么做最好的方法?是否有通用解决方案?

How to realize parallel loop in Delphi (Delphi 200X, Delphi XE) ? How to do this best way? And is there any universal solution?

请提供示例。

推荐答案

当时是 OmniThreadLibrary 中的Parallel For Loop构造。您传递一个集合,或一对代表下限和上限的整数,以及一个代表循环体的匿名方法,它使用一个线程池并行运行for循环。

Probably the best solution at the moment is the Parallel For Loop construct in OmniThreadLibrary. You pass it a collection, or a pair of integers representing lower and upper bounds, and an anonymous method representing the loop body, and it uses a thread pool to run the for loop in parallel.

请注意,只有在循环体方法能够独立存在的情况下,这才有效。如果它修改任何外部变量或依赖于循环中较早的计算值,那么它将无法并行化。

Note that this will only work if the loop body method is capable of standing on its own. If it modifies any external variables or relies on the value of a calculation made earlier in the loop then it can't be parallelized.

对于OmniThreadLibrary并行的介绍可以 here 。例如,一个简单的循环遍历数字,如下所示:

An introduction to the OmniThreadLibrary parallel for can be found here. For example, a simple for loop iterating over numbers looks like this:

Parallel.ForEach(1, testSize).Execute(
  procedure (const elem: integer)
  begin
    // do something with 'elem'
  end);

这篇关于如何在Delphi中实现并行循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆