SimplifyC++ Article
Unleashing Parallel Power C++ Code for Concurrent Array Processing with Multithreading
Unleashing Parallel Power: C++ Code for Concurrent Array Processing with Multithreading
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 likestd::reduce.<numeric>: For usingstd::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 usingstd::reducewith thestd::execution::parexecution policy to enable parallel processing.main:Create a vector of arrays: A vector
arraysis created, containing three integer arrays.Create a vector of futures: A vector
futuresis created to store the futures (std::future) that represent the results of the parallel processing tasks.Launch parallel tasks: A
forloop is used to launch an asynchronous task (std::async) for each array inarrays. TheprocessArrayfunction and the current array are passed as arguments to the task. The resulting future is stored in thefuturesvector.Wait for tasks to complete: Another
forloop 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::asyncandstd::future. You can replaceprocessArraywith any other operations you want to perform on the arrays.You need to have the thread library (
std::thread) supported in your development environment.