C/C++ Programming Abstractions for Parallelism and Concurrency – Part 2

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.

  • Pingback: C/C++ Programming Abstractions for Parallelism and Concurrency – Part 1 | Red Hat Developer Blog()

  • Awesome tutorial. But looking for some deep insights on the future replacement for ‘std::async’ in C++ standard. Looking forward for some complex threading examples using Intel’s TBB and how well it works across platforms.
    Also I am wondering whether is it possible for C++ runtime to create threads, the same way Erlang creates process(lightweight and OS independent). I have no idea about Erlang and its processes but just read about it, that they create processes which are very lighter than kernel threads and can operate independent of the underlying Operating System.
    Thank you.

    • Torvald Riegel

      The future of std::async is under discussion in ISO C++ Study Group 1 (SG1 for short) in particular, with suggestions ranging from deprecating it to extending it or replacing it with something else; nothing final has been decided yet. SG1 has also been discussing a proposal called Executors, which tries to give programmers more control about how things are executed. (Note that the proposal itself is relatively concrete and for specific use cases, but the discussions cover the more general questions.) The Executors discussions also touch on your second question regarding light-weight threads; C++11 just gives you “full” OS threads via std::thread, but providing lighter-weight execution agents (e.g., regarding how they interact with thread-local-storage) has been discussed as well, aiming both at the execution of parallel tasks and for other proposals that are on the table.

      There will be an ISO C++ meeting at the end of September, where these topics will likely be discussed again. I will see whether it’s worthwhile to summarize the current state in a blog post afterwards.

      • raja26

        Thanks a lot for the reply. I am a Ruby on Rails developer, who constantly pursue C++ knowledge, since it is my first love ;-). For laymen like me, it would be awesome if you explain how the discussions will take place in ISO C++ mettings. Will it be like

        * Let us make the threads light as Erlang does.
        * Let us make them easier for programmers like Go does.
        * Let us make it consistent with other popularly used C++ threading libraries, like Open MP, Qt threading.
        * Let us make it future proof.

        Basically what I am asking is, will the new features be compared with other language features (which are better in that particular feature) or is it entirely based on C++?

  • Pingback: Our Top 12 Blog Articles of 2013 | Red Hat Developer Blog()

  • Pingback: C++ 11 Parallel and Concurrent Programming | mybookmarks()

  • Pingback: OpenMP 4.0 support in Developer Toolset 3 Beta — Parallel programming extensions for today’s architectures | Red Hat Developer Blog()

  • Pingback: Intelⓡ Threading Building Blocks in Red Hat Enterprise Linux 7 | Red Hat Developer Blog()