Parallel For Loops

Parallel For Loops are a hassle-free way to supercharge your program with the Parallel Programming Library. The syntax is similar to the standard For loop, with the advantage of each iteration running on in a different task on the thread pool. This allows multiple iterations to run at the same time, taking advantage of the multi-core and hyper-threaded architecture common on laptops, desktops and mobile devices today.

Here is the replay of the Skill Sprint:

Here are the slides:

Update: I was chatting with Allen Bauer today and he mentioned that while you technically can use Queue and Synchronize from within a Parallel For loop, he wouldn’t recommend it because it will dramatically reduce the speed of the loop. It is still faster than a linear loop, but not as fast as it could be. I’ll leave these examples here, but keep that in mind when optimizing your parallel code.

Here is the syntax in Object Pascal. The stride is the first parameter is it is optional. It controls how the iterations are grouped when being sent to the CPUs. Min and Max are your usual start and stop range for the loop. The last parameter is an anonymous method that represents the code to be executed on each iterations. It takes an Index parameter that is either an Integer or Int64 that provides the value of the current iteration.

TParallel.For(Stride, Min, Max, procedure (Idx: Integer)
begin
  if IsPrime(Idx) then
  begin
    TInterlocked.Increment (Tot);
    TThread.Queue(TThread.CurrentThread, procedure
    begin
      Memo1.Lines.Add(Idx.ToString);
    end);
  end;
end);

Here is the C++ code syntax. It takes a event instead of an anonymous method.

// . . .
TParallel::For(NULL, Min, Max, MyIteratorEvent);
// . . . 

void __fastcall TFormThreading::MyIteratorEvent(TObject *Sender, int AIndex)
{
	if(IsPrime(AIndex)){
		TInterlocked::Increment(Tot);
	};
}

There are some great blog posts and videos on the Parallel Programming Library

Stephen Ball has a series of blog posts on the Parallel Programming Library, including a Quick Introduction and one on managing the thread pool. As Stephen points out, while you can customize the thread pool, that doesn’t alway mean you should. Malcolm Groves also has some great blog posts on PPL.

Danny Wind has a great Code Rage 9 session on the Parallel Programming Library (be sure to download his samples). David I. did the C++ version.

Allen Bauer, our Chief Scientist, also has a CodeRage 9 session on the PPL Architecture.

If you want to take advantage of the new C++11 Lambda syntax on Win64 and mobile, then check out this community article or watch this CodeRage 9 video snippet. Get Bruneau and David’s code for C++ and Parallel libraries.

Update: Keep in mind that a Parallel For loop isn’t always the best performance option, but it is really easy to use. Check out Stefan Glienke’s Stack Overflow answer for an alternative using the PPL TTask for even better performance.

Posted in Android, Architecture, iOS, Mobile, Source Code | 6 Comments

Delphi Hackathon

How are you Delphi programming skills? Want to visit Fortaleza, Brazil? I’m sure it is especially nice if you are in the northern hemisphere right now since Brazil is enjoying summer while we are stuck in winter.

Next week Hack’n Fortes is hosting a Delphi hackathon / programming marathon. Registration is closed, but you can always head down to watch. If Brazil is a little far away, we have an online Code Battle planned for Wednesday the 15th as part of Delphi Week 2015! #DelphiWeek

Posted in News | Leave a comment

Looking at Radiant Shapes

RadiantShapes_Logo
I’ve been playing with Raize Software‘s new Radiant Shapes components this week. These are the brand new primitive shape component set for FireMonkey on all platforms: Windows, OS X, iOS and Android. I’ve been a long time fan of Raize Components because of their attention to detail and high quality. Radiant Shapes continues this tradition.

Radiant Shapes PaletteRadiant Shapes is made up of 35 reusable shape controls that are all pretty flexible. If you caught Ray Konopka’s RAD In Action: Seeing is Believing on Data Visualization then you have a pretty good idea the importance of using primitive shapes like these to communicate useful information to your users, especially in mobile development.

All of the shapes include useful design time menus to make common changes quickly and easily. You can probably get away without using the Object Inspector for a lot of your common tasks. They also have various customizations that make them very flexible.

One thing that is interesting is they introduce the idea of a TRadiantDimension they allows you to specify some of the sizes as either absolute pixels, or as a scale factor. This gives great flexibility in how they behave when resized.

Ray Konopka introduced the Radiant Shapes during CodeRage 9 with a couple great sessions. You can catch the replay for both Object Pascal and C++.

I really like the TRadiantGear component, so I decided to play with it in detail. You can specify the number of cogs (teeth), their size (as a Radiant Dimension) and the size and visibility of the hole. Just like all the other shapes, they handle hit tests correctly, so at runtime, you can click between the cogs of the gear and it doesn’t produce an onClick event.

Gears

Just for fun I put down three gears and used LiveBindings to connect a TTrackBar.Value to their rotation. A little math in the OnAssigningValue event and I had all the gears rotating in unison. The fact that the gears stayed synced up, and the teeth meshed perfectly was really impressive.

procedure TForm4.RotateGearBigAssigningValue(Sender: TObject;
  AssignValueRec: TBindingAssignValueRec; var Value: TValue;
  var Handled: Boolean);
begin
  Value := TValue.From(-1 * (Value.AsExtended / 2 + 18));
end;

procedure TForm4.RotateGearRightAssigningValue(Sender: TObject;
  AssignValueRec: TBindingAssignValueRec; var Value: TValue;
  var Handled: Boolean);
begin
  Value := TValue.From(-1 * (Value.AsExtended + 18));
end;

18 is the offset for the gears (360° / 10 cogs / 2 (half offset) = 18) and the 2 comes from the big gear being twice as big (20 cogs), then the -1 is so they rotate the opposite direction.

Overall I am impressed with the Radiant Shapes. Something I would like to see include a polygon component where I can specify the number of sizes. You can do that with the star and gear, but a flexible polygon would be nice. Also, the shapes can be rotated with the rotation property, but it would be cool if there was a way to rotate it in the designer too. That might be a big undertaking though.

You can buy the Radiant Shapes from Raize Software for $49, which gives you a 1 year subscription for updates. I did get a complimentary copy from Raize Software to review them.

Be sure to join Ray on Friday the 23rd as he is featured in the Embarcadero Technology Partner Spotlight.

Posted in Android, design, iOS, Tools | 3 Comments

Episode #55 – Interview with JT

An interview with John Thomas “JT”, Senior Director of Product Management over RAD Studio and Delphi with Embarcadero Technologies.This episode was recorded almost a year and a half ago, right after the XE5 release added Android support, but is still a relevant conversation today.

It is 2 weeks from our last episode, so we are going to try and keep it at an episode every 2 weeks for now and see how that goes. Also we are moving to Soundcloud for audio hosting.

Posted in Audio podCast, podcast | Leave a comment

Run Outside the Handler or Making a Non-Blocking Call

Have you ever had some code you wanted to run outside of the event handler that causes the code to run? If not, then this blog post isn’t for you. I’m not here to debate why you would want to do that, or if it is a good idea or not. I just know there’ve been times I’ve needed my code to run outside the event handler, or just a bit later.

One use case example: You are calling a slow routine (Network I/O maybe) and don’t want to freeze the UI while you wait for it to execute.

Still with me? Good. What I used to do was drop a TTimer on the form and set the Interval to 1, then enable it to trigger the code to run later. This worked, but it was messy. You had a timer to deal with, and you had to remember to disable it in the event handler, so it didn’t run multiple times. You also could have used a TThread, which may have been a better solution, but still seemed kind of messy, especially if you wanted to update the UI from your code.

Thanks to the new System.Threading library introduced with XE7, I’ve created a simple procedure that makes this a breeze to do. I call the procedure NonBlocking, but you could just as easily call it RunALittleLaterRunOutsideHandler, etc.

uses System.Threading;

procedure NonBlocking(const Proc: TThreadProcedure);
begin
  TTask.Create(procedure begin
    TThread.Queue(nil, Proc);
  end).Start;
end;

All this does is create a task, and then inside the task queue an update back to the main thread to execute the code that is passed to this procedure as an anonymous method. You could easily just write this code inline, but I thought it worthwhile creating a procedure to handle it for me.

Lets look at a normal execution scenario:

  //...
  ListBox1.Items.Add('Before Handler');
  EventHandler;
  ListBox1.Items.Add('After Handler');
  //....

procedure TForm1.EventHandler;
begin
  ListBox1.Items.Add('Inside Handler');
end;

When this is run, our ListBox1 will look like

  • Before Handler
  • Inside Handler
  • After Handler

which is what we would expect. Now when we introduce a call to our new procedure in the EventHandler:

  //...
  ListBox1.Items.Add('Before Handler');
  EventHandler;
  ListBox1.Items.Add('After Handler');
  //....

procedure TForm1.EventHandler;
begin
  ListBox1.Items.Add('Inside Handler 1');
  NonBlocking(procedure begin
    ListBox1.Items.Add('Outside Handler'); // This will run last
  end);
  ListBox1.Items.Add('Inside Handler 2');
end;

Our ListBox1 will look like

  • Before Handler
  • Inside Handler 1
  • Inside Handler 2
  • After Handler
  • Outside Handler

Notice that Outside Handler was the very last line added, even though it is written between Inside Handler 1 and Inside Handler 2. It even occurs after the After Handler line. Also, this works across all platforms: iOS, Android, Windows and OS X.

Everything before and within the call to NonBlocking will execute in order, but the code within NonBlocking will execute after the code that comes after that anonymous method.

If you have a ShowMessage or something else that blocks the UI thread in the event handler, then the code you passed to the NonBlocking procedure will be executed early, which is fine since the UI thread was already blocked.

 

Posted in Source Code | 7 Comments

Delphi and the #Code2014 Rankings

The Twitter #Code2014 ranking have become a bit of a tradition. At the end of the year everyone votes for the  programming languages they used, or were their favorite for the year. Then they all get tabulated up to see how they rank. Once again Delphi did quite well, coming it at #9, just ahead of other mainstream languages like C and C++ as well as niche languages like Objective-C and Swift (developing for only one platform is so 2013). It was neck and neck with C#, ending with only 11 votes different.

Delphi finished 9th in the #Code2014 rankings on Twitter

Delphi finished 9th in the #Code2014 rankings on Twitter

There are actually still people voting, but the deadline was Friday, so the votes don’t count. I still appreciate the enthusiasm. Watching Delphi climb the charts was a real treat, and shows two things:

  1. Delphi is still a very popular language
  2. The Delphi community is amazing

I believe this second point to be the most important one. The community really came together to vote for Delphi and move it up the rankings. Makes me happy to be part of such an amazing community.

 # Language Count
 1 javascript 2414
 2 python 1355
 3 java 1317
 4 ruby 1044
 5 sql 936
 6 php 882
 7 bash 871
 8 c# 814
 9 delphi 803
 10 c 692
 11 c++ 598
 12 go 566
 13 clojure 504
 14 haskell 452
 15 scala 449
 16 objective-c 375
 17 swift 343
 18 livecode 280
 19 coffeescript 262
 20 f# 246

Looking at the top languages, they mostly have a web development theme. I’ve heard before that Twitter seems to have a web development bias, and this seems to reinforce that. Also since you are allowed to vote for more than one language we see SQL with a very high ranking, even though I imagine it had very few votes just for it (I may be wrong, but it seems like the kind of language you use with a general purpose language).

 

Posted in News | 14 Comments

Episode 54 – Sarina DuPont

Welcome back to the Podcast at Delphi.org. This is my first podcast since I’ve started working for Embarcadero Technologies back in 2013. When I first started I’d planned to resurrect the podcast, but got caught up with all the new projects, travel and excitement and it fell by the wayside.

With the New Year it seems fitting to recommit to the podcast. I’ve got a lot of changes planned. I’m not sure about the frequency format and other details, but figure it is better to get a rolling start.

I actually recorded this interview with Sarina DuPont (@SarinaDuPont) back in August of 2013, right before the RAD Studio XE5 release added Android support. So some of the comments are dated in that regard, but most of it is still relevant. So while XE5, XE6 and XE7 have all shipped since the podcast, Sarina is still a product manager and the focus of getting to know her and her vision for RAD Studio is still relevant.

[Download]

Typically I am in the Scotts Valley office about one week a month. My plan is to start recording some interviews when I am there. I’ve really enjoyed getting to know people behind the scenes with my favorite development tools, and hope you will too.

In the next episode I’ll have an interview with John Thomas (@FireMonkeyPM), or JT, the Senior Director of Product Management here at Embarcadero Technologies.

Oh, and check out the new Embarcadero Community Podcast by David I.

Posted in Audio podCast, podcast | 5 Comments

Tweet Delphi #Code2014

If you code in Delphi, then be sure to Tweet Delphi #Code2014 to have your vote counted. I’ve made it really easy for you, if you just log into Twitter and click the link you cast your vote. You can see the rankings on Code2014.com or just check the list of all the tweets for Delphi.

Vote, and tell your friends to vote. They filter to one per Twitter account.

Posted in News | Leave a comment

Mobile Push Notifications without a BaaS

Delphi, C++Builder and RAD Studio XE7 include support for mobile push (remote) notifications via a Parse and Kinvey BaaS providers. This makes it really easy to send push notifications to your users on mobile devices. Both Parse and Kinvey offer free service levels (as well as paid), and you can also download App42 SDK for Appmethod and use the App42 BaaS instead.

BaaS or Backend As A Service Providers are companies that maintain the backend servers necessary for many application development tasks. They handle things like user authentication, data storage, push notifications, etc. Sometimes they are referred to as mBaaS or Mobile-BaaS because if the heavy focus on mobile application development these days, but they typically are not tied to mobile.

This doesn’t mean you have to use a BaaS provider to send mobile push notifications. This is just the easy way. During CodeRage we’ve had sessions on how to do push notifications without a BaaS provider. It is different for both iOS and Android, so you are looking at a lot more code and effort, but it is possible.

CodeRage 9 had a session by Jeff LeFebvre had a session on Android Push notifications via Google Cloud Messaging (GCM):

Here is a transcript of the Q&A as well as download links.

For iOS & iPhone use of Apple Push Notifications (APN) Luis Felipe and Anders Ohlsson have some blog posts and videos on the subject. Luis did the original post and video in Spanish, and then Anders translated and expanded on it.

Luis’ post on iOS notifications with XE4 (Spanish but you can use Google Translate). It includes some source code downloads too. The video is also in Spanish but it shows a lot of source code, so it is easy enough to follow along.

Ander’s blog post expanding on it (English), and his CodeRage video on the subject (English)

Keep in mind that this is about the same level of complexity to use most other tools for sending and receiving push notifications.

Posted in Android, iOS, Mobile | 1 Comment

Last Minute Christmas Shopping Ideas

If you still have a few people on your Christmas gift list that you just don’t know what to do for, check out the RAD Offer page. You’ll save some serious money, and they will get the best development tool for building highly connected multi-device native apps.

Get Free Bonuses with the purchase of RAD Studio XE7,
Delphi XE7 and C++Builder XE7 until December 31, 2014

Rapid SQL XE6
Rapid SQL® is the intelligent SQL IDE empowering database developers and DBAs the ability to create high-performing SQL code on all major databases from a single interface. Purchase RAD Studio, Delphi and C++Builder XE7 Enterprise or above and receive a license of Rapid SQL XE6. Redeem your license.

New Object Pascal Handbook by Marco Cantu
This brand new 300-page ebook is a complete guide to the current, modern Object Pascal programming language by best-selling Delphi books author and Delphi Senior Product Manager Marco Cantu. This new language manual for new & existing Object Pascal developers covers core language features, object-oriented programming with Object Pascal, and the latest language features like generics, anonymous methods, and reflection in todays’ Delphi compilers.

Mida Converter Basic
Mida Basic for RAD Studio XE7 is a special edition of the popular VCL to FireMonkey converter. Helps converting your VCL forms to multi-device, including data bindings and other advanced features with support for over 200 components.

Castalia for Delphi
Castalia is a premier code productivity plug-in for Delphi. With code refactoring, structural highlighting, parenthesis matching, flow control, highlighting, and live syntax checking, Castalia makes you more productive than ever. Use project statistics and code analysis to better understand your team productivity and code quality.

VCL and FireMonkey
Premium Styles

Customize the look of your VCL Windows applications with five premium styles including Coral, Diamond, Emerald, Sterling or Jet style. Customize your multi-device applications with seven premium FireMonkey styles including Jet, Sterling, Diamond, Emerald Crystal, Emerald Dark, Coral Crystal and Coral Dark styles.

FastCube VCL 2
FASTCUBE VCL is a set of OLAP Desktop components and a tool for effective data analysis. FastCube enables you to analyze data and to build summary tables (data slices) as well as create a variety of reports and graphs both easily and instantly. It’s a handy tool for the efficient analysis of data arrays.

Availability: Rapid SQL XE6 is available on Enterprise and above ESD purchases from Oct 20-December 31, 2014 (network licenses do not qualify). Other bonus pack items are available on purchases from Oct 1-December 31, 2014.See qualifying SKUs.

How to get it: After purchasing, click here to get your free bonus items. (Redeem free items within 14 days of offer expiration date). Not available with purchase of Starter edition.

Restrictions Apply. Not all products qualify for this offer.

Upgrade from any previous version and save up to 45%

Get the upgrade price on Delphi XE7, C++Builder XE7 or RAD Studio XE7 through December 31, 2014 regardless of what previous version you have. Save up to 45% off the regular new user price for the product license and stay up-to-date with automatic enrollment in the Recharge program.

Availablility: All eligible XE7 purchases from Oct 20-December 31, 2014. See qualifying SKUs.

Download and activate your trial and get
Coding in Delphi by Nick Hodges for free.

By activating your trial, you will receive a free copy of Coding in Delphi. This ebook covers a variety of powerful Delphi programming features and techniques including Generics, Interfaces, Exception Handling, Anonymous Methods and more!

How to get it: After activating your trial, click here to download the ebook.

Posted in News | Leave a comment