Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Splitting work into chunks
    4. How many threads
    5. std::reduce instead of std::accumulate
    6. Parallel algorithms: std::execution::par
    7. Floating-point sums change in parallel
    8. Measuring the speedup
    9. Amdahl’s law
    10. Which one should I use?
    11. Under the hood
    12. Common pitfalls
    13. A shared total inside a parallel algorithm
    14. Dropping the leftover elements
    15. An exception inside a parallel algorithm
    16. Try it yourself

    Module 10 · Concurrency

    10.3Parallel work

    Split one big job across every core: chunks with one partial result per thread, std::reduce and the parallel algorithms with std::execution::par, measuring the speedup, Amdahl's law, and why parallel floating-point sums come out slightly different.

    About 30 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. Splitting work into chunks
    4. How many threads
    5. std::reduce instead of std::accumulate
    6. Parallel algorithms: std::execution::par
    7. Floating-point sums change in parallel
    8. Measuring the speedup
    9. Amdahl’s law
    10. Which one should I use?
    11. Under the hood
    12. Common pitfalls
    13. A shared total inside a parallel algorithm
    14. Dropping the leftover elements
    15. An exception inside a parallel algorithm
    16. Try it yourself

    Key terms

    chunk
    One contiguous piece of the input, such as elements 0 to 249,999, that a single thread works through on its own.
    partial result
    What one thread computes for its chunk. The partial results are combined into the final answer after the threads finish.
    execution policy
    An extra first argument to a standard algorithm that says how it may run: std::execution::seq (one thread), par (several threads) or par_unseq (several threads and vector instructions). From <execution>.
    TBB
    oneAPI Threading Building Blocks, a C++ library of thread pools and parallel loops. GCC's standard library runs the parallel algorithms on it; link it with -ltbb.
    speedup
    How many times faster the parallel version is: the time on one thread divided by the time on several.
    Amdahl's law
    The speedup is limited by the part of the work that can't be split: if 10% of the run stays serial, no number of threads makes it more than 10 times faster.
    memory-bound
    Work whose speed is limited by how fast memory delivers the data, not by the arithmetic. More threads help it little.
    thread pool
    A fixed set of threads started once and reused for many small tasks, so you don't pay to start a thread per task.

    A computer with many cores runs a one-thread program on one of them and leaves the rest idle. To use them all on one job, such as adding up a billion numbers or scoring a million reads, you split the input into pieces, let each thread work on its own piece, and combine the pieces’ results at the end. This lesson does that by hand with threads, then lets the standard library do it for you, and shows how to tell whether it paid off.

    In 30 seconds

    • Split the input into one chunk per thread. Each thread writes its partial result to its own slot; after join, combine the slots in order. No locks needed.
    • std::reduce is std::accumulate that may add in any order, so it can be split up. Give it std::execution::par and it runs on several threads.
    • Measure: the speedup is rarely the number of cores. Small inputs and memory-bound work gain little, and Amdahl’s law caps the rest.
    • Floating-point addition isn’t associative: a parallel sum of floats or doubles can differ in the last digits from a serial one.

    Splitting work into chunks

    To add up a big vector on several threads, give each thread a range of indices. Each thread adds its range into a local variable, then stores it in partials[t], a slot no other thread touches. Nothing is shared that two threads write, so there’s no data race and no mutex. After every thread has finished, main adds up the slots.

    #include <algorithm>
    #include <cstddef>
    #include <numeric>
    #include <print>
    #include <thread>
    #include <vector>
    
    long long parallel_sum(const std::vector<int>& values, std::size_t threads) {
        std::vector<long long> partials(threads, 0);
        std::size_t chunk = values.size() / threads;
        {
            std::vector<std::jthread> workers;
            for (std::size_t t = 0; t < threads; ++t) {
                std::size_t first = t * chunk;
                std::size_t last = t + 1 == threads ? values.size() : first + chunk;
                workers.emplace_back([&values, &partials, t, first, last] {
                    long long sum = 0;
                    for (std::size_t i = first; i < last; ++i) {
                        sum += values[i];
                    }
                    partials[t] = sum;
                });
            }
        } // each jthread joins here, when workers is destroyed
        return std::accumulate(partials.begin(), partials.end(), 0LL);
    }
    
    int main() {
        std::vector<int> values(1'000'000);
        std::iota(values.begin(), values.end(), 1); // 1, 2, 3, ...
        std::size_t threads = std::max(1u, std::thread::hardware_concurrency());
        std::println("{}", parallel_sum(values, threads));
        std::println("{}", parallel_sum(values, 3));
    }

    Output

    500000500000
    500000500000

    A few details carry the whole design:

    • The last chunk ends at values.size(), so it also takes the leftover elements when the size doesn’t divide evenly.
    • The lambda captures values and partials by reference (they outlive the threads) and t, first and last by value (they change on the next loop step).
    • std::jthread joins in its destructor (Threads shows how), so the inner { } block ends only when every thread is done. Reading partials before that would be a data race.
    • Each thread adds into its own local sum and writes partials[t] once. Writing partials[t] += values[i] for every element would be correct but slow: the slots sit next to each other in one cache line, and threads writing neighboring bytes slow each other down. That’s false sharing, covered in Mutexes and atomics.

    The answer is the same for any number of threads, because integer addition gives the same total in any grouping.

    How many threads

    std::thread::hardware_concurrency() returns how many threads the hardware can run at once, or 0 if it can’t tell, hence the std::max(1u, …) (1u is an unsigned 1, because both arguments of std::max must have the same type). More threads than that don’t make CPU work faster: they take turns on the same cores. For work that waits on memory, fewer threads are often just as fast. Start with the hardware count and measure.

    std::reduce instead of std::accumulate

    Iterators and algorithms showed both. std::accumulate adds strictly left to right: ((0 + a) + b) + c. That fixed order is exactly what you can’t split up. std::reduce is allowed to group and reorder the additions any way it likes, which is what splitting into chunks does.

    That freedom has a price: the operation must give the same answer in any grouping (it must be associative, (a + b) + c == a + (b + c)) and in any order (commutative, a + b == b + a). Addition and multiplication of integers, std::max and std::min qualify. Subtraction doesn’t, and std::reduce doesn’t check:

    #include <functional>
    #include <numeric>
    #include <print>
    #include <vector>
    
    std::vector<int> values = {10, 1, 2, 3, 4, 5, 6, 7, 8};
    int in_order =
        std::accumulate(values.begin(), values.end(), 0, std::minus<>{});
    int regrouped =
        std::reduce(values.begin(), values.end(), 0, std::minus<>{});
    std::println("accumulate: {}", in_order);
    std::println("reduce:     {}", regrouped);

    Output

    accumulate: -46
    reduce:     -18

    std::minus<>{} is the - operator as a function object. std::accumulate computes 0 - 10 - 1 - … - 8. std::reduce grouped the values differently (GCC’s library combines them in groups of four, even without threads) and got another answer. Nothing reports a problem; the second result is just meaningless.

    Parallel algorithms: std::execution::par

    Most standard algorithms take an execution policy as an extra first argument. #include <execution> and pass one of these:

    PolicyMeaning
    std::execution::seqOne thread, in order. The same as leaving the policy out, except for how exceptions are handled (see the pitfalls).
    std::execution::parMay run on several threads. Your function must be safe to call from several threads at once.
    std::execution::par_unseqMay run on several threads and also with vector instructions, interleaving several calls on one thread. Your function must not lock a mutex or call anything that might, such as allocating memory.

    The policy is a permission, not an order: the library may still use one thread for a small input.

    #include <algorithm>
    #include <execution>
    #include <numeric>
    #include <print>
    #include <vector>
    
    std::vector<double> scores(1'000'000);
    for (std::size_t i = 0; i < scores.size(); ++i) {
        scores[i] = static_cast<double>(i * 7919 % 1000); // 0 to 999, mixed
    }
    std::sort(std::execution::par, scores.begin(), scores.end());
    std::for_each(std::execution::par_unseq, scores.begin(), scores.end(),
                  [](double& s) { s = s / 2.0; });
    double total =
        std::reduce(std::execution::par, scores.begin(), scores.end());
    std::println("lowest {}, highest {}", scores.front(), scores.back());
    std::println("total {}", total);

    Output

    lowest 0, highest 499.5
    total 249750000

    The std::for_each lambda touches only its own element, so it is safe on any number of threads. GCC’s standard library runs par and par_unseq on TBB, so a program that uses them must be linked with it: add -ltbb at the end of the g++ command (in CMake, find_package(TBB REQUIRED) and link TBB::tbb). If TBB isn’t installed when you compile, GCC’s library quietly runs the parallel algorithms on one thread.

    Floating-point sums change in parallel

    Floating-point addition rounds after every step, so it isn’t associative: grouping the same numbers differently can give a different sum. Here, one big value and 999,999 ones are added in order, then in four chunks the way four threads would add them:

    #include <cstddef>
    #include <numeric>
    #include <print>
    #include <vector>
    
    std::vector<float> values(1'000'000, 1.0f);
    values[0] = 1e8f;
    float in_order = std::accumulate(values.begin(), values.end(), 0.0f);
    
    float in_chunks = 0.0f; // four chunks, as four threads would add them
    for (std::size_t first = 0; first < values.size(); first += 250'000) {
        auto begin = values.begin() + static_cast<std::ptrdiff_t>(first);
        in_chunks += std::accumulate(begin, begin + 250'000, 0.0f);
    }
    double exact = std::accumulate(values.begin(), values.end(), 0.0);
    std::println("in order:  {:.0f}", in_order);
    std::println("in chunks: {:.0f}", in_chunks);
    std::println("exact:     {:.0f}", exact);

    Output

    in order:  100000000
    in chunks: 100750000
    exact:     100999999

    Near 100,000,000, a float can only hold every eighth whole number, so 1e8f + 1.0f rounds straight back to 1e8f. In order, every one of the ones is lost. In chunks, three of the four chunks add their ones to each other first (250,000 fits exactly), so only the 249,999 ones in the first chunk are lost. Neither float result is right; adding in double is.

    With std::reduce(std::execution::par, …) the grouping depends on how TBB splits the work, which can change from run to run. Two runs on the same data can then print different last digits:

    #include <execution>
    #include <numeric>
    #include <print>
    #include <vector>
    
    std::vector<float> values(10'000'000, 0.1f);
    float serial = std::accumulate(values.begin(), values.end(), 0.0f);
    float parallel =
        std::reduce(std::execution::par, values.begin(), values.end());
    std::println("accumulate: {}", serial);
    std::println("reduce par: {}", parallel);

    Output from one run (it varies)

    accumulate: 1087937
    reduce par: 999771.6

    The parallel sum is closer to the true 1,000,000 here, because it adds small partial sums together instead of adding each 0.1f to an ever larger total. For tests that compare floating-point results, allow a small tolerance (Testing shows WithinRel), or sum in double.

    Measuring the speedup

    Only a measurement tells you whether parallel code is faster. This program times three jobs with std::execution::seq and with par: adding 20 million doubles, computing std::sqrt(x) * std::sin(x) for each of them and adding the results, and adding only 1,000 of them. The second job uses std::transform_reduce from <numeric>: it calls heavy on each element and combines the results with std::plus<>{} (the + operator as a function object) in one pass, without storing them in between. It’s built with -O2 and without sanitizers, like any timing (Module 9’s caches lesson explains why).

    #include <chrono>
    #include <cmath>
    #include <execution>
    #include <functional>
    #include <numeric>
    #include <print>
    #include <vector>
    
    double heavy(double x) {
        return std::sqrt(x) * std::sin(x);
    }
    
    template <typename Policy>
    double run(Policy policy, const std::vector<double>& v, bool cheap) {
        if (cheap) {
            return std::reduce(policy, v.begin(), v.end());
        }
        return std::transform_reduce(policy, v.begin(), v.end(), 0.0, std::plus<>{},
                                     heavy);
    }
    
    void compare(const char* name, const std::vector<double>& v, bool cheap) {
        using ms = std::chrono::duration<double, std::milli>;
        auto t0 = std::chrono::steady_clock::now();
        double serial = run(std::execution::seq, v, cheap);
        auto t1 = std::chrono::steady_clock::now();
        double parallel = run(std::execution::par, v, cheap);
        auto t2 = std::chrono::steady_clock::now();
        ms seq_time = t1 - t0;
        ms par_time = t2 - t1;
        std::println("{:<12} seq {:8.3f} ms  par {:8.3f} ms  speedup {:5.1f}x  "
                     "difference {:.1e}",
                     name, seq_time.count(), par_time.count(), seq_time / par_time,
                     serial - parallel);
    }
    
    int main() {
        std::vector<double> big(20'000'000, 1.5);
        std::vector<double> small(1'000, 1.5);
        run(std::execution::par, big, true); // warm-up: starts TBB's threads
        compare("sum, 20M", big, true);
        compare("sqrt*sin", big, false);
        compare("sum, 1000", small, true);
    }

    Output from one run (it varies)

    sum, 20M     seq   11.781 ms  par    3.132 ms  speedup   3.8x  difference 0.0e+00
    sqrt*sin     seq   77.090 ms  par    8.707 ms  speedup   8.9x  difference -1.1e-04
    sum, 1000    seq    0.001 ms  par    0.008 ms  speedup   0.1x  difference 0.0e+00

    In this run, on the machine that checks this site’s examples (24 hardware threads), the plain sum got about 4 times faster, the sqrt/sin job about 9 times faster, and the 1,000-element sum several times slower. Your numbers will differ with the machine and from run to run, but the pattern is typical:

    • Adding numbers is memory-bound. One addition takes far less time than fetching the next 8 bytes from RAM, and all cores share the same memory bus, so a few threads already use all the bandwidth there is. See Caches.
    • Lots of arithmetic per element scales well. Each thread spends its time computing, not waiting for memory. It still falls well short of 24 times: hardware threads often come two to a core and share its arithmetic units, and the serial parts (see Amdahl’s law below) don’t shrink.
    • Small inputs lose. Handing out the work and collecting the results costs microseconds, more than adding 1,000 numbers.

    The difference column is the serial result minus the parallel one: zero for the sums of 1.5 (every partial sum is exact) and tiny but not always zero for sqrt*sin, as the previous section explained.

    PerformanceTime it with a warm-up and an optimized build

    The first parallel call starts TBB’s worker threads, so time a second call, not the first. Build with -O2 and without sanitizers, use the result (here it’s printed), and run it a few times: the numbers change from run to run.

    Amdahl’s law

    Most programs have parts that can’t be split: reading the input, combining partial results, printing. If a fraction p of the run time can be spread over n threads and the rest can’t, the best possible speedup is

    speedup = 1 / ((1 - p) + p / n)
    

    With 90% parallel work (p = 0.9):

    #include <print>
    
    double p = 0.9; // the part of the run time that can be split up
    for (int n : {1, 2, 4, 8, 16, 1000}) {
        double speedup = 1.0 / ((1.0 - p) + p / n);
        std::println("{:>4} threads: {:.1f}x", n, speedup);
    }

    Output

       1 threads: 1.0x
       2 threads: 1.8x
       4 threads: 3.1x
       8 threads: 4.7x
      16 threads: 6.4x
    1000 threads: 9.9x

    Eight threads give less than 5 times, and a thousand give less than 10: the serial 10% takes the same time however many threads run the rest. To go faster, shrink the serial part, not only add threads.

    Which one should I use?

    Should this loop run in parallel?
    1. Is the input small (thousands of elements, under a millisecond of work)?

      Yes

      Keep it serialStarting the parallel work costs more than it saves.

      No
    2. Does each element depend on the one before it?

      Yes

      Keep it serial, or rethink the algorithmA running total or a state machine can't be cut into independent chunks.

      No
    3. Is it a standard algorithm: sort, transform, a sum or count with an associative operation?

      Yes

      Pass std::execution::parThen measure the speedup.

      No
    4. Otherwise: Split it into chunks on your own threads, one partial result per thread

    WhatWhenWhyHow
    std::accumulate or a loopSmall inputs, or the order of operations matters.Simple, predictable, same result every run.std::accumulate(v.begin(), v.end(), 0.0)
    std::reduce / std::transform_reduce with parLarge inputs and an associative, commutative operation.One line; TBB splits the work and balances it across cores.std::reduce(std::execution::par, v.begin(), v.end())
    par_unseqThe same, and the function never locks or allocates.Also allows vector instructions inside each thread.std::for_each(std::execution::par_unseq, …)
    Your own threads and chunksThe job isn’t one standard algorithm, or each thread needs its own state (a map of counts, a buffer).Full control over what each thread does and how results combine.std::jthread per chunk, a partials slot each

    Rule of thumb: reach for a parallel algorithm first, write chunks by hand when you need per-thread state, and keep whichever one the stopwatch says is faster.

    Under the hood

    Starting a thread is slow next to adding a few numbers: the operating system has to create it, give it a stack and schedule it. So the parallel algorithms don’t start threads per call. TBB keeps a thread pool: about one worker per hardware thread, started the first time you use it and kept waiting for work.

    When you call std::reduce(std::execution::par, …), GCC’s library hands the range to TBB, which cuts it in half, and the halves in half again, until the pieces are small. Each worker takes pieces from its own list. A worker that runs out takes a piece from another worker’s list; this is called work stealing, and it keeps every core busy even when some pieces take longer than others. That’s also why the grouping of a parallel floating-point sum can change between runs.

    Your hand-written chunks do the same thing more simply: equal pieces, one per thread, fixed in advance. That’s fine when every element costs the same. When some elements are much more expensive (long and short reads, say), cut the work into many more chunks than threads and let each thread take the next unclaimed one, which is a small thread pool of your own. Processing reads in parallel feeds workers through a queue this way.

    Common pitfalls

    A shared total inside a parallel algorithm

    par runs your function on several threads at once. Adding into one captured variable from all of them is a data race, the same bug as in Threads. ThreadSanitizer catches it:

    #include <algorithm>
    #include <execution>
    #include <print>
    #include <vector>
    
    std::vector<int> values(100'000, 1);
    long long total = 0;
    std::for_each(std::execution::par, values.begin(), values.end(),
                  [&total](int v) { total += v; });
    std::println("{}", total);

    This fails when it runs

    WARNING: ThreadSanitizer: data race
      Read of size 8 at 0x… by thread T1:
        #0 operator() main.cpp:9
           … 13 frames inside the standard library
    
      Previous write of size 8 at 0x… by main thread:
        #0 operator() main.cpp:9
           … 15 frames inside the standard library
    
      Location is stack of main thread.
    
      Thread T1 (running) created by main thread at:
        #0 pthread_create
           … 4 frames inside the standard library
    
    SUMMARY: ThreadSanitizer: data race main.cpp:9 in operator()

    Use a reduction instead. It gives each thread its own partial total, as the chunks above did:

    #include <execution>
    #include <numeric>
    #include <print>
    #include <vector>
    
    std::vector<int> values(100'000, 1);
    long long total =
        std::reduce(std::execution::par, values.begin(), values.end(), 0LL);
    std::println("{}", total);

    Output

    100000

    A std::atomic<long long> total (Mutexes and atomics) would also be correct, but every thread would fight over the same cache line, often slower than one thread.

    Dropping the leftover elements

    values.size() / threads rounds down: 10 elements on 4 threads give chunks of 2, and if every chunk has that size, elements 9 and 10 belong to no chunk. The sum quietly leaves them out, with no error from any tool. Let the last chunk end at values.size(), as parallel_sum does, and test with sizes that don’t divide evenly.

    An exception inside a parallel algorithm

    If your function throws while running under seq, par or par_unseq, the program doesn’t get the exception: it calls std::terminate and stops. Only the version without a policy passes exceptions on to your catch. Check for bad input before the parallel call, or return an error value from each element instead of throwing.

    Try it yourself

    Try it yourself

    highest finds the best quality score on one thread. Make it split the work across threads std::jthreads, each finding the maximum of its own chunk, then combine the chunk maximums. (The threads parameter has its name in a comment for now, because the starter doesn’t use it yet.) Both calls must still print 41.

    #include <algorithm>
    #include <cstddef>
    #include <print>
    #include <thread>
    #include <vector>
    
    int highest(const std::vector<int>& qualities, std::size_t /*threads*/) {
        return *std::max_element(qualities.begin(), qualities.end());
    }
    
    int main() {
        std::vector<int> qualities = {30, 12, 38, 25, 41, 18, 33, 40, 7, 29};
        std::println("{}", highest(qualities, 4));
        std::println("{}", highest(qualities, 3));
    }

    Expected output

    41
    41
    Show a hint

    Copy the shape of parallel_sum: a partials vector with one slot per thread, a chunk size, the last chunk ending at qualities.size(), and an inner block of jthreads. Each thread finds the maximum of its range; main takes the maximum of the slots.

    Show a solution
    #include <algorithm>
    #include <cstddef>
    #include <print>
    #include <thread>
    #include <vector>
    
    int highest(const std::vector<int>& qualities, std::size_t threads) {
        std::vector<int> partials(threads, 0);
        std::size_t chunk = qualities.size() / threads;
        {
            std::vector<std::jthread> workers;
            for (std::size_t t = 0; t < threads; ++t) {
                std::size_t first = t * chunk;
                std::size_t last =
                    t + 1 == threads ? qualities.size() : first + chunk;
                workers.emplace_back([&qualities, &partials, t, first, last] {
                    int best = 0;
                    for (std::size_t i = first; i < last; ++i) {
                        best = std::max(best, qualities[i]);
                    }
                    partials[t] = best;
                });
            }
        }
        return *std::max_element(partials.begin(), partials.end());
    }
    
    int main() {
        std::vector<int> qualities = {30, 12, 38, 25, 41, 18, 33, 40, 7, 29};
        std::println("{}", highest(qualities, 4));
        std::println("{}", highest(qualities, 3));
    }

    Each thread writes only partials[t], and main reads the slots after the inner block has joined every thread, so there's no data race. Maximum is associative and commutative, so the maximum of the chunk maximums is the maximum of everything, whatever the number of threads.

    Saved in this browser only.