I tried to implement simple for loop running on custom number of threads like this:
#include <thread>
template<typename func, typename... args>
void threadFor(int numOfThreads, int repeats, func f, args... a)
{
auto forPart = [&](int repeats){
for (int i = 0; i < repeats; ++i) f(i, a...);
};
int part = repeats / numOfThreads;
int remainder = repeats % numOfThreads;
std::thread threads[numOfThreads];
for (int i = 0; i < numOfThreads; ++i)
{
threads[i] = std::thread(forPart,part + (i < remainder));
}
for (int i = 0; i < numOfThreads; ++i) threads[i].join();
}
I am testing it in the following way:
#include <iostream>
void increment(int i, int* j){++*j;}
int main()
{
int j = 0;
threadFor(8,1000000, increment, &j);
std::cout << j;
}
When I execute the code, j is less than 1,000,000. Also, the code sometimes crushes because of double deletion or segmentation error. What am I doing wrong?
std::thread threads[numOfThreads];is not valid c++. Use avectorinstead.