Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

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

August 20, 2013
Torvald Riegel
Related topics:
Developer Tools
Related products:
Developer Tools

Share:

    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 ...
      task.join();
      // ... 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 ...
    task.get();

    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:
      0,
      // 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

    Recent Posts

    • How Kafka improves agentic AI

    • How to use service mesh to improve AI model security

    • How to run AI models in cloud development environments

    • How Trilio secures OpenShift virtual machines and containers

    • How to implement observability with Node.js and Llama Stack

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue