Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

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

August 20, 2013
Torvald Riegel
Related topics:
Developer tools
Related products:
Developer Toolset

    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

    • Debugging image mode with Red Hat OpenShift 4.20: A practical guide

    • EvalHub: Because "looks good to me" isn't a benchmark

    • SQL Server HA on RHEL: Meet Pacemaker HA Agent v2 (tech preview)

    • Deploy with confidence: Continuous integration and continuous delivery for agentic AI

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    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
    © 2026 Red Hat

    Red Hat legal and privacy links

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

    Chat Support

    Please log in with your Red Hat account to access chat support.