Quick summary ↬ Here is an example of C++ threading code that demonstrates how to use multiple threads to calculate the sum of an array of numbers. I will provide a detailed explanation of the code afterwards.
Beautiful code #7
|
|
Beautiful code #7 explanation
First, we include the necessary header files for working with threads, such as <iostream>
, <vector>
, <thread>
, and <numeric>
.
We define the sumPartialArray function, which calculates the sum of a portion of the array. It takes in the array, the start index, and the end index as parameters and uses std::accumulate to perform the summation.
In the main function, we declare two constants: numThreads represents the number of threads to use, and arraySize represents the size of the array.
We create and initialize the array of integers from 1 to arraySize.
We create a vector of threads called threads to store the threads we will launch.
To calculate the sum using multiple threads, we divide the array into equal-sized blocks based on the number of threads. We calculate the blockSize by dividing arraySize by numThreads. Then, we initialize start as 0 and end as blockSize.
We enter a loop to launch a thread for each portion of the array. Inside the loop, we assign a thread to each element in the threads vector using the std::thread constructor. We pass the sumPartialArray
function, along with the array, start index, and end index, as arguments.
After launching all the threads, we use another loop to wait for each thread to finish its execution using the join member function of each thread.
Finally, we combine the partial sums calculated by each thread by iterating over the threads
You will also like — More Articles
https://fluentprogrammer.com/beautiful-code-1-using-define-templates-r-value-reference/ https://fluentprogrammer.com/beautiful-code-2-enable_if_t-template-inside-a-template/ https://fluentprogrammer.com/beautiful-code-3-no_unique_address_cpp_20-feature/ http://fluentprogrammer.com/beautiful-code-4-any_of-none_of-all_of/ https://fluentprogrammer.com/beautiful-code-5-for_each-optional/