Parallelizing Loops

Both GenerateAESKeys and GenerateMD5Hashes represent an opportunity to run iterations in parallel. They generate the input data to simplify the example and perform the same operation for each piece. Thus, it represents a data parallelism scenario. It is possible to refactor the loops to run the operations in parallel. This way, instead of running both subroutines in parallel, each one can take full advantage of parallelism and automatically scale according to the number of existing logical cores.

Parallel.For

You can think of refactoring an existing For loop to take advantage of parallelism as a simple replacement of For with Parallel.For. Unfortunately, it isn't as simple as that.

The following code snippets refactor the subroutines shown in the preceding section, showing the code for both the original loops and the new code with the refactored loops using the imperative syntax to implement the data parallelism offered by Parallel.For. The new methods, ParallelGenerateAESKeys and ParallelGenerateMD5Hashes, try to take advantage of all the cores available, relying on the work done under the hood by Parallel.For to optimize its behavior according to the existing hardware at runtime.

1. The original GenerateAESKeys subroutine with the sequential For loop, and its parallelized version
  • Original sequential For version (code file: Listing02.sln):
 Sub GenerateAESKeys()
     Dim sw = Stopwatch.StartNew()
     Dim aesM As New AesManaged()
     For i As Integer = 1 To NUM_AES_KEYS ...

Get Professional Visual Basic 2012 and .NET 4.5 Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.