Article by Ayman Alheraki on January 11 2026 10:32 AM
void processArray(const std::vector<int>& arr) { // Perform desired operations on the array here int sum = std::reduce(std::execution::par, arr.begin(), arr.end()); std::cout << "Sum of array: " << sum << std::endl;}
int main() { std::vector<std::vector<int>> arrays = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };
std::vector<std::future<void>> futures;
for (const auto& arr : arrays) { futures.push_back(std::async(std::launch::async, processArray, arr)); }
// Wait for all tasks to complete for (auto& future : futures) { future.wait(); }
return 0;}
Code Explanation:
#include: Include necessary libraries:
<iostream>: For standard input/output.
<vector>: For using dynamic arrays.
<thread>: For creating and managing threads.
<future>: For handling values that will be returned from threads in the future.
<algorithm>: For using standard algorithms like std::reduce.
<numeric>: For using std::reduce.
<execution>: For specifying the parallel execution policy.
processArray: A function that processes a single array. In this example, it calculates the sum of the array elements using std::reduce with the std::execution::par execution policy to enable parallel processing.
main:
Create a vector of arrays: A vector arrays is created, containing three integer arrays.
Create a vector of futures: A vector futures is created to store the futures (std::future) that represent the results of the parallel processing tasks.
Launch parallel tasks: A for loop is used to launch an asynchronous task (std::async) for each array in arrays. The processArray function and the current array are passed as arguments to the task. The resulting future is stored in the futures vector.
Wait for tasks to complete: Another for loop is used to wait for all launched tasks to finish.
Technologies Used:
std::async: Used to launch asynchronous tasks, allowing them to execute in separate threads.
std::future: Used to store the results of asynchronous tasks and wait for them to complete.
std::reduce: Used to calculate the sum of array elements.
std::execution::par: Used to specify the parallel execution policy, allowing the standard library to divide the work among the available threads.
Notes:
This code demonstrates how to process a set of arrays in parallel using std::async and std::future. You can replace processArray with any other operations you want to perform on the arrays.
You need to have the thread library (std::thread) supported in your development environment.