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

Output Code

Uploaded by

frediaxle6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

Output Code

Uploaded by

frediaxle6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include <iostream>

#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
#include <thread>
#include <future>
#include <mutex>

std::mutex mtx;

void parallel_sum(const std::vector<int>& data, int start, int end,


std::promise<int>&& result) {
int sum = std::accumulate(data.begin() + start, data.begin() + end, 0);
result.set_value(sum);
}

int main() {
const int size = 1000000;
std::vector<int> data(size);
std::iota(data.begin(), data.end(), 1);

const int num_threads = std::thread::hardware_concurrency();


std::vector<std::future<int>> futures;
int chunk_size = size / num_threads;

for (int i = 0; i < num_threads; ++i) {


std::promise<int> result;
futures.push_back(result.get_future());
int start = i * chunk_size;
int end = (i == num_threads - 1) ? size : start + chunk_size;
std::thread(parallel_sum, std::cref(data), start, end,
std::move(result)).detach();
}

int total_sum = 0;
for (auto& future : futures) {
total_sum += future.get();
}

std::cout << "Total Sum: " << total_sum << std::endl;


return 0;
}

You might also like