Search⌘ K
AI Features

Solution: Safe vs. Unsafe Parallelism

Understand how std::reduce combined with std::execution::par enables safe parallel computations in C++. Discover why std::reduce avoids data races by working on partial sums and merging results thread-safely. This lesson helps you grasp safe parallel algorithm implementation for improved performance without risking unsafe shared state modifications.

We'll cover the following...
C++ 23
#include <iostream>
#include <vector>
#include <algorithm>
#include <execution>
#include <numeric>
int main() {
std::vector<int> sensor_readings(10'000'000, 1);
// We replace the unsafe side-effect loop with std::reduce
// std::reduce automatically handles partitioning and combining results
// from multiple threads safely
long long total_energy = std::reduce(
std::execution::par,
sensor_readings.begin(),
sensor_readings.end()
);
std::cout << "Total Energy: " << total_energy << "\n";
std::cout << "Expected: 10000000\n";
if (total_energy == 10'000'000) {
std::cout << "Status: Success (Safe Parallelism)\n";
} else {
std::cout << "Status: Failure (Incorrect Result)\n";
}
return 0;
}
...