Welcome to part 2 of this two-part article on C/C++ Programming Abstractions for Parallelism and Concurrency.  If you missed Part 1, view it here.

Supporting task-based parallelism

Let us now switch from concurrency to parallelism. I already mentioned that C++11 and C11 provide support for creating threads that execute additional work in parallel or concurrently. However, these facilities are rather resource abstractions (i.e., for operating system threads) than abstractions aimed purely at parallelism. One target for the latter is often task-based parallelism, which allows programmers to split a part of a program into tasks (i.e., units of work). These tasks will run in parallel, but they can also depend on other tasks in which case a dependent task will not start executing until all it's dependencies are fulfilled (e.g., until a prior task has finished generating output that constitutes input for the current task). This essentially creates a directed acyclic graph (DAG) of tasks; tasks that are not ordered in the DAG wrt. each other can execute in parallel.

So, how can programmers express that they want to run a parallel task? When managing threads explicitly using the thread abstractions (explicit threading for short), this may look like this:

try {
  auto task = std::thread(work); // Execute the work() function
  // ... Do something else ...
  // ... Use the task's result ...
catch (std::system_error e) { error_fallback(); }

We explicitly create a new thread and join the thread (i.e., wait for it to complete its work) at task dependencies. We need error handling and a fallback in case we cannot create another thread for some reason.

In contrast, with abstractions aimed at tasks, we create tasks that may execute in another or a new thread:

auto task = std::async(work);
// ... Do something else ...

Instead of requiring the programmer to manage threads, a task scheduler provided by the abstraction (e.g., std::async()) manages typically a set of threads and decides when to execute which tasks on which thread.  (Note that std::async is used as an example here; it has limitations that lead the ISO C++ committee to discuss whether it should be deprecated once a better replacement is part of the standard.)

This might not seem like a big difference compared to explicit threading at first, but high-performance explicit threading can quickly become difficult in nontrivial applications. For example, how many threads should a programmer create? Too few threads, and there is a lack of parallelism and thus performance. Too many, and this will result in less locality and a larger memory-system footprint, so also less-than-optimal performance. It may seem straightforward at first to just use as many threads as CPU cores in the system, but what if our parallel code is invoked from an already parallel caller? Even if the programmer tries to use a thread pool, which tasks should be executed when and on which thread? How do we coordinate with other thread pools that might be used  elsewhere in the application or by libraries?

Abstractions for task-based parallelism try to not burden programmers with such questions, and instead provide facilities meant to let programmers focus on the core task: expressing parallelism in the program. Intel's Threading Building Blocks (TBB), which are included in Fedora, provide such abstractions. Here is an example for how to compute the sum of all elements in an array:

int sum = tbb::parallel_reduce(
  // The input array, which will be partitioned automatically:
  tbb::blocked_range<int*>(array, array + size),
  // Identity value for the sum reduction:
  // Task (as a lambda) that returns the sum of all elements in a partition:
  [](const tbb::blocked_range<int*>& r, int v) {
    for (auto i=r.begin(); i!=r.end(); ++i) v += *i;
      return v;
  // Reduction operation (as a lambda) that combines the per-partition sums:
  [](int x, int y) { return x+y; }

This will partition the array automatically, compute the sum of all elements in each partition using a suitable number of threads from an internal thread pool, and combine the results of all the partitions into one final result that is returned from the parallel_reduce() function call.

Facilities for certain patterns of parallelism such as a parallel reduction in this example allow programmers to express parallelism in a much denser way. TBB supports further patterns such as parallel iterations, sorting, or message passing with tasks.

Outlook and summary

Parallelization of programs is important to exploit the parallelism that recent hardware offers. While explicit threading provides tight control over how hardware resources are used for parallel execution, it is more complex and can be more difficult to get right (e.g., wrt. to modularity) than when relying on programming abstractions for task-based parallelism such as those provided by TBB. When writing parallel or concurrent programs, always pay attention to data races, and synchronize where necessary to avoid them. Pick the right programming abstraction for synchronization that provides the best trade-off between programming complexity, performance, and required skills for the problem that you are trying to solve: Atomics, locks, and transactions all have their place. Starting with an easier-to-use abstraction can be useful; often, synchronization bottlenecks can be avoided more easily by increasing parallel execution (i.e., by avoiding the need for synchronization) than by trying to optimize the synchronization code itself (e.g., by writing complex code based on atomics).

While C11 and C++11 provide a good foundation, more programming abstractions for parallelism and concurrency will likely be added to future versions of these language standards. ISO C++ Study Group 1 is working on standardizing various abstractions ranging from concurrent data structures to task parallelism, and Study Group 5 is working on TM. Furthermore, there are other standards such as OpenMP that have been supported by GCC for a long time, and support for OpenMP 4.0 is currently being developed in a branch of upstream GCC. Cilk+ is another set of language extensions for parallelism for which support is being developed in upstream GCC. Both OpenMP 4.0 as well as Cilk+ also provide abstractions for exploiting SIMD parallelism, which is important due to hardware vector support becoming increasingly powerful even on mainstream CPUs.

Red Hat is participating in these standardization and implementation efforts, and we would like to hear your feedback. Atomics, transactional memory, and other C++11 concurrency and parallelism features are available today in GCC-4.7 in Red Hat Developer Toolset; GCC-4.8, which Red Hat expects to release in an update to Red Hat Developer Toolset later this year and which is available as a Beta release now, further improves the support for parallelism and concurrency.

Last updated: February 22, 2024