Fluent::Programmer

    Home Blog About
  • Home
  • Blog
  • About

Beautiful code #7 - std::thread, std::accumulate 👋

  • Fluent Programmer
  •   4 min read

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <vector>
#include <thread>
#include <numeric>

// Function to calculate the sum of a portion of the array
int sumPartialArray(const std::vector<int>& array, int start, int end) {
    return std::accumulate(array.begin() + start, array.begin() + end, 0);
}

int main() {
    const int numThreads = 4;  // Number of threads to use
    const int arraySize = 1000000;  // Size of the array

    // Create and initialize the array
    std::vector<int> array(arraySize);
    for (int i = 0; i < arraySize; ++i) {
        array[i] = i + 1;
    }

    // Create a vector of threads
    std::vector<std::thread> threads(numThreads);

    // Calculate the sum using multiple threads
    int blockSize = arraySize / numThreads;
    int start = 0;
    int end = blockSize;

    std::vector<int> partialSums(numThreads);  // Vector to store partial sums

    for (int i = 0; i < numThreads; ++i) {
        // Launch a thread to calculate the sum of a portion of the array
        threads[i] = std::thread([&array, start, end, i, &partialSums]() {
            partialSums[i] = sumPartialArray(array, start, end);
        });

        // Update the start and end indices for the next thread
        start = end;
        end += blockSize;
    }

    // Wait for all the threads to finish
    for (auto& thread : threads) {
        thread.join();
    }

    // Combine the partial sums calculated by each thread
    int totalSum = std::accumulate(partialSums.begin(), partialSums.end(), 0);

    std::cout << "Total sum: " << totalSum << std::endl;

    return 0;
}

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/

You may like this

About The Author

Fluentprogrammer doesn't need coffee to program. They run on pure caffeine and lines of code.

Email Newsletter

Table of Contents

  • Beautiful code #7
  • Beautiful code #7 explanation
  • You will also like — More Articles
  • You may like this
  • C++
  • Beautiful code series

Unhealthy love with dark corners of C++

Founded by an engineer to help engineers. 2021–2023.

  • About us
  • Privacy policy