Delphi D10.X 并行库PPL编程之 Futures


本文整理自网络,侵删。

 
Delphi D10.X 并行库PPL编程系列之 Futures

delphi中的RTL(运行库)提供了并行编程库(PPL --Parallel Programming Library) ,让您的应用程序可以在跨平台应用中有效的使用多个CPU并行运行任务的能力。
Futures 让流程专注于其他任务,然后在所需的位置获得该流程的结果。IFuture允许您为运行的代码块建立优先级,并在需要时仍返回结果。

Futures 说明

Future接受一个能够在并行线程中运行的函数,并返回一个接口,该接口用于在程序中所需位置获取结果。

Future方法将IFuture的实例返回到类型T定义的变量中。类型参数T表示要在并行线程中运行的函数的返回类型。

以下是不同的重载方法:

class function Future<T>(Sender: TObject; Event: TFunctionEvent<T>): IFuture<T>; overload; static; inline;
class function Future<T>(Sender: TObject; Event: TFunctionEvent<T>; APool: TThreadPool): IFuture<T>; overload; static; inline;
class function Future<T>(const Func: TFunc<T>): IFuture<T>; overload; static; inline;
class function Future<T>(const Func: TFunc<T>; APool: TThreadPool): IFuture<T>; overload; static; inline;

Futures演示

使用Futures时,将会在需要时获得此值,如果尚未计算,它将阻塞直到完成。

演示中使用到的控件


只需要两个按钮控件,其中一个用于启动计算,另一个用于获取计算执行结果。

添加使用单元

首先,我们需要引用PPL库:

uses
  System.Threading; // 需要引用PPL库

设置一个变量

  public
    { Public declarations }
    FutureString: IFuture<string>;

分别为两个按钮增加处理事件

{=======================  Future 演示  ========================================}
procedure TForm5.Button4Click(Sender: TObject);
begin
  FutureString:= TTask.Future<string>(
    function:string
    begin
      {暂停一段时间,模拟需要计算的处理时间 }
      Sleep(3000);
      Result:='Hello ' + Random(42).ToString;
  end);
end;

procedure TForm5.Button5Click(Sender: TObject);
begin
  Button5.Text := FutureString.Value;
end;
{=======================  Future 演示  ========================================}

演示效果
――――――――――――――――

点击启动按钮后,在3秒内点击获取结果后,会阻塞直到我们程序里的3秒结束后,返回一个42以内的随机数。

原文链接:https://blog.csdn.net/tanqth/article/details/104554661

相关阅读 >>

Delphi yesterday、today、tomorrow - 昨天、今天、明天

Delphi 长文件路径转换短文件路径

Delphi tstatusbar 用来显示当前程序状态的

Delphi 从字符串提取字符串

Delphi 标头控件(theadercontrol)中的显示复选框

Delphi 判断 文本文件 utf-8 bom头

Delphi图片增加文字水印

Delphi 实现文件防删除非亢占(非hook)

Delphi串口通信编程

Delphi 返回程序执行参数的例子

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...