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!