Using dynamic arrays and Parallel Programming Library (Part 1)

The Parallel Programming Library introduced in XE7 is one of the  most awaited built-in library for the Delphi and C++Builder RTL, at least for me. I’ve still a nice list waiting for the next versions, but this is another story 🙂

Marco Cantù wrote about dynamic arrays some days ago, another nice feature introduced in Delphi XE7. In the post he talk about an integration between Parallel Programinng Library and dynamic arrays which I shown to the audience in the Milan and Rome XE7 world tour.

I planned to write about Parallel Programming Library in this blog, so why don’t start with that simple example?

Here’s the code.

procedure TFormThreading.Button1Click(Sender: TObject);
var
  tasks: array of ITask;
  value: Integer;
begin
  value := 0;
  tasks := [
  TTask.Create(procedure
    begin
      sleep(1000); // 1 seconds
      TInterlocked.Add(value, 1000);
    end).Start,

  TTask.Create(procedure
    begin
      sleep(3000); // 3 seconds
      TInterlocked.Add(value, 3000);
    end).Start,

  TTask.Create(procedure
    begin
      sleep(5000); // 5 seconds
      TInterlocked.Add(value, 5000);
    end).Start
    ];

  TTask.WaitForAll(tasks);
  ShowMessage('All done: ' + value.ToString);
end;

This code configure and start 3 parallel tasks and wait for their completitions. Then show the result using a ShowMessage.
This code takes 5 second to be executed because the 1st second there are 3 tasks running, from 2nd second to the 3rd second there are 2 tasks running while the last 2 seconds only one task is running. All the internal threads are managed by a thread pool. Hey! This means parallelize!

4 thoughts on “Using dynamic arrays and Parallel Programming Library (Part 1)

  1. Hi,
    thank you for your example. But how would it be possible to write this code so it becomes better readable?

    This anonymous stuff looks really uggly.

    I wish to be able to write something like this:

    procedure TFormThreading.Button1Click(Sender: TObject);

    var
    tasks: array of ITask;
    value: Integer;

    procedure MyTask(SomeNumber:integer);
    begin
    sleep(SomeNumber);
    TInterlocked.Add(value, SomeNumber);
    end

    begin
    value := 0;
    tasks[0]:=TTask.Create(MyTask(1000)).Start;
    tasks[1]:=TTask.Create(MyTask(3000)).Start;
    tasks[2]:=TTask.Create(MyTask(5000)).Start;
    TTask.WaitForAll(tasks);
    ShowMessage(‘All done: ‘ + value.ToString);
    end;

  2. How do you think about the follow code:

    type
    TDynAry = array of Integer;
    TByteSet = set of Byte;

    procedure Test1(V: TDynAry); overload;
    begin
    end;

    procedure Test1(V: TByteSet); overload;
    begin
    end;

    procedure TForm2.Button1Click(Sender: TObject);
    begin
    Test1([1, 2]); //Call the set function
    //I try this code: Test1(TDynAry([1, 2]));
    // compiler error.
    end;

    So, the feature is a partially prepared products.

Comments are closed.