0% found this document useful (0 votes)
7 views1 page

Writing Parallel Algorithms For Parallel Vector Addition

The document presents a C++ program that implements parallel vector addition using threads. It defines a function to add segments of two vectors and utilizes two threads to perform the addition concurrently. The result is printed as a vector where each element is the sum of corresponding elements from the input vectors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views1 page

Writing Parallel Algorithms For Parallel Vector Addition

The document presents a C++ program that implements parallel vector addition using threads. It defines a function to add segments of two vectors and utilizes two threads to perform the addition concurrently. The result is printed as a vector where each element is the sum of corresponding elements from the input vectors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

Writing parallel algorithms for parallel vector addition

#include <iostream>
#include <vector>
#include <thread>

using namespace std;

// Function to add a part of two vectors


void addVectors(const vector<int>& A, const vector<int>& B, vector<int>& C, int start, int end) {
for (int i = start; i < end; i++) {
C[i] = A[i] + B[i];
}
}

int main() {
int size = 10;
vector<int> A(size, 1); // All 1s
vector<int> B(size, 2); // All 2s
vector<int> C(size); // Result vector

// We'll use 2 threads for simplicity


thread t1(addVectors, cref(A), cref(B), ref(C), 0, size / 2);
thread t2(addVectors, cref(A), cref(B), ref(C), size / 2, size);

t1.join();
t2.join();

// Print the result


cout << "Result vector: ";
for (int val : C) {
cout << val << " ";
}

return 0;
}

Output:
Result vector: 3 3 3 3 3 3 3 3 3 3

 std::thread uses std::ref()/std::cref() under the hood to manage arguments safely.

 To support that, many implementations include <functional> inside <thread>, making


ref() and cref() available to you implicitly.

You might also like