Task

Get to learn what tasks are and how they are performed.

parallel()

Operations that are executed in parallel with other operations of a program are called tasks. Tasks are represented by the type std.parallelism.Task.

In fact, parallel() constructs a new Task object for every worker thread and starts that task automatically. parallel() then waits for all of the tasks to be completed before finally exiting the loop. parallel() is very convenient as it constructs, starts, and waits for the tasks automatically.

Handling tasks explicitly

When tasks do not correspond to or cannot be represented by elements of a range, these three steps can be handled explicitly by the programmer. task() constructs, executeInNewThread() starts, and yieldForce() waits for a task object. These three functions are explained further in the comments of the following program. The anOperation() function is started twice in the following program. It prints the first letter of id to indicate which task it is working for (Line 14).

Note: Normally, the characters that are printed to output streams like stdout do not appear on the output right away. They are instead stored in an output buffer until a line of output is completed. Since write does not output a new-line character, in order to observe the parallel execution of the following program, stdout.flush() is called to send the contents of the buffer to stdout even before reaching the end of a line.

Get hands-on with 1400+ tech skills courses.