taskPool.parallel()

You will learn about the working of the parallel() function in this lesson.

Working of taskPool.parallel() function

This function can also be called simply as parallel().

parallel() accesses the elements of a range in parallel. An effective usage is with foreach loops. Merely importing the std.parallelism module and replacing students with parallel(students) as done previously, is sufficient to take advantage of all of the cores of the system:

import std.parallelism; 
// ...
    foreach (student; parallel(students)) {

We have seen earlier in the foreach for structs and classes chapter that the expressions that are in foreach blocks are passed to opApply() member functions as delegates. parallel() returns a range object that knows how to distribute the execution of the delegate to a separate core for each element.

As a result, passing the Student range through parallel() makes the program below finish in 1 second on a system that has 4 cores:

Get hands-on with 1200+ tech skills courses.