I'm reading about multithreads with C++. My code is to compute the sum of elements using multithread approach. The code is
#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
void func(std::atomic<long long>& sum, const std::vector<long long>& vec)
{
long long result(0);
for(int i(0); i < vec.size(); ++i){
result += vec[i];
}
sum += result;
}
int main()
{
// create a variable to hold the result.
std::atomic<long long> sum(0);
// create vector of threads
std::vector<std::thread> threads;
// generate numbers
std::vector<long long> num;
for(long long i(1); i<=10000000; ++i)
num.push_back(i);
// each thread should compute the sum of some numbers
long long k(0);
//create 1,000 threads
for(int i(0); i<1000; ++i){
// extract elements from the big elements vector (i.e. in this example, each thread handles 10,000)
std::vector<long long> temp(&num[k],&num[k+10000]);
k+=10000;
threads.push_back(std::thread{ func, std::ref(sum), temp });
}
for(auto& t : threads){
t.join();
}
std::cout << "Sum = " << sum << std::endl;
return 0;
}
I would like to know if my code can be enhanced more. The comments should be enough to explain the code. Thank you.