As a part of a uni project I have to create a program which can have an arbitrary amount of threads given as a command line argument. I first tried making a dynamic array of threads like this:
thread* threads = new thread[numThreads]; ( Note: I want to use the threads class, not pthreads ). I figured it didn't work because to my knowledge new tries to call default constructors to thread, which it doesn't have and lator on I cannot actually construct the threads properly. Then I tried to do it in the following way:
thread** threads = new thread*[numThreads];
for (int i = 0; i < numThreads; i++)
{
threads[i] = new thread(calculateFractal, width, height, numThreads, i, fractal, xmin, xmax, ymin, ymax, xStepSize, yStepSize, maxNorm);
}
I have defined the function and all of the used variables in the aforementioned constructors in the for are of their appropriate data types:
void calculateFractal(int& width, int& height, int& numThreads, int& thisThreadNum, RGB**& fractal,
long double& xmin, long double& xmax,long double& ymin, long double& ymax,
long double& xStepSize, long double& yStepSize, long double& maxNorm)
This code still doesn't work and gives the same compiler errors(C2672 and C2893) for essentially inappropriate function template as if I have not passed the correct type of arguments. Can you figure out what is wrong with the code?
vector<thread> threads(num_threads, thread(calculateFractal, width, height, numThreads, i, fractal, xmin, xmax, ymin, ymax, xStepSize, yStepSize, maxNorm));would be the first thing I'd try.thread a_thread(calculateFractal, width, height, numThreads, i, fractal, xmin, xmax, ymin, ymax, xStepSize, yStepSize, maxNorm);. Have you tried that?The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g., with std::ref or std::cref).std::threaddoes have a default constructor so your first approach (although better done with a vector) should work. Please show a minimal reproducible example with the full code and full error messagefractal, isn't it?