Parallel Tasks

Distributing CPU-bound work across a thread pool and collecting results.

What This Example Shows

Source Code

#include <boost/capy.hpp>
#include <iostream>
#include <latch>
#include <sstream>
#include <thread>

namespace capy = boost::capy;

// Sum integers in [lo, hi)
capy::task<capy::results<long long>> partial_sum(int lo, int hi)
{
    std::ostringstream oss;
    oss << "  range [" << lo << ", " << hi
        << ") on thread " << std::this_thread::get_id() << "\n";
    std::cout << oss.str();

    long long sum = 0;
    for (int i = lo; i < hi; ++i)
        sum += i;
    co_return capy::results<long long>{std::error_code(), sum};
}

int main()
{
    constexpr int total = 10000;
    constexpr int num_tasks = 4;
    constexpr int chunk = total / num_tasks;

    capy::thread_pool pool(num_tasks);
    std::latch done(1);

    auto on_complete = [&done](auto&&...) { done.count_down(); };
    auto on_error = [&done](std::exception_ptr ep) {
        try { std::rethrow_exception(ep); }
        catch (std::exception const& e) {
            std::cerr << "Error: " << e.what() << "\n";
        }
        catch (...) {
            std::cerr << "Error: unknown exception\n";
        }
        done.count_down();
    };

    auto compute = [&]() -> capy::task<> {
        std::cout << "Dispatching " << num_tasks
                  << " parallel tasks...\n";

        auto [ec, s0, s1, s2, s3] = co_await capy::when_all(
            partial_sum(0 * chunk, 1 * chunk),
            partial_sum(1 * chunk, 2 * chunk),
            partial_sum(2 * chunk, 3 * chunk),
            partial_sum(3 * chunk, 4 * chunk));

        long long total_sum = s0 + s1 + s2 + s3;

        // Arithmetic series: sum [0, N) = N*(N-1)/2
        long long expected =
            static_cast<long long>(total) * (total - 1) / 2;

        std::cout << "\nPartial sums: " << s0 << " + " << s1
                  << " + " << s2 << " + " << s3 << "\n";
        std::cout << "Total: " << total_sum
                  << " (expected " << expected << ")\n";
    };

    capy::run_async(pool.get_executor(), on_complete, on_error)(compute());
    done.wait();

    return 0;
}

This page shows a variant that uses the variadic when_all overload, so each partial sum gets its own name. The program in example/parallel-tasks/ uses the range overload over a std::vector of tasks instead. Both print the same output.

Build

add_executable(capy_example_parallel_tasks parallel_tasks.cpp)
target_link_libraries(capy_example_parallel_tasks PRIVATE Boost::capy)

Walkthrough

Partitioning Work

constexpr int total = 10000;
constexpr int num_tasks = 4;
constexpr int chunk = total / num_tasks;

The range [0, 10000) is divided into 4 equal chunks, one per task. Each task computes a partial sum independently.

Parallel Execution with when_all

auto [ec, s0, s1, s2, s3] = co_await capy::when_all(
    partial_sum(0 * chunk, 1 * chunk),
    partial_sum(1 * chunk, 2 * chunk),
    partial_sum(2 * chunk, 3 * chunk),
    partial_sum(3 * chunk, 4 * chunk));

when_all starts all four tasks concurrently on the thread pool. The result is results<long long, long long, long long, long long>, a single ec plus the four partial sums in input order.

Observing Thread IDs

std::ostringstream oss;
oss << "  range [" << lo << ", " << hi
    << ") on thread " << std::this_thread::get_id() << "\n";
std::cout << oss.str();

On a multi-core system you typically see different thread IDs, which shows the tasks running in parallel. One worker can also take several tasks, so some IDs may repeat. Building each line in an ostringstream and writing it with one << reduces interleaving between threads.

Verifying Results

The sum of [0, N) is N*(N-1)/2. The example verifies that the sum of partial results matches this formula.

Output

Dispatching 4 parallel tasks...
  range [0, 2500) on thread 140234567890432
  range [2500, 5000) on thread 140234567886336
  range [5000, 7500) on thread 140234567882240
  range [7500, 10000) on thread 140234567878144

Partial sums: 3123750 + 9373750 + 15623750 + 21873750
Total: 49995000 (expected 49995000)

Exercises

  1. In example/parallel-tasks/parallel_tasks.cpp, construct the pool with 2 threads and set num_tasks to 8, then observe how the pool shares the tasks between its threads

  2. Add a timing comparison between parallel execution and a single-threaded loop

  3. Generalize the partitioning to handle ranges that don’t divide evenly

Next Steps