作为uni项目的一部分,我必须创建一个程序,该程序可以具有任意数量的线程作为命令行参数。我首先尝试制作一个动态的线程数组,如下所示:thread* threads = new thread[numThreads];
(注意:我要使用线程类,而不是pthreads)。我发现它没有用,因为据我所知,新尝试将默认构造函数调用为线程,而默认构造函数没有该线程,因此我实际上无法正确构造线程。然后,我尝试通过以下方式进行操作:
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);
}
我已经定义了函数,并且for中上述构造函数中使用的所有变量都是其适当的数据类型: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)
对于本质上不合适的函数模板,此代码仍然无法正常工作,并给出相同的编译器错误(C2672和C2893),就好像我没有传递正确的参数类型一样。您能弄清楚代码有什么问题吗?
最佳答案
使用std::vector<std::thread>
,如下所示
std::vector<std::thread> threadsVec(threadsNumber);
for(size_t i{}; i < threadsNumber; ++i){
threadsVec[i] = std::thread{.....};
}
并且当您放置args时,请确保在函数需要引用时使用std::ref(arg)
,因为std::thread
仅接受rvalues
,因此您必须引入std::reference_wrapper
以下是一个完整的工作示例#include <thread>
#include <iostream>
#include <vector>
struct RGB{};
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){
std::cout << "inside the thread";
}
int main()
{
int width, height, thisThreadNum;
RGB fractal1;
RGB* fractal2 = &fractal1;
RGB** fractal3 = &fractal2;
long double xmin, xmax, ymin, ymax, xStepSize, yStepSize, maxNorm;
int threadsNumber = 1;
std::vector<std::thread> threadsVec(threadsNumber);
for(size_t i{}; i < threadsNumber; ++i){
threadsVec[i] = std::thread{calculateFractal, std::ref(width), std::ref(height),
std::ref(threadsNumber), std::ref(thisThreadNum), std::ref(fractal3),
std::ref(xmin), std::ref(xmax), std::ref(ymin), std::ref(ymax),
std::ref(xStepSize), std::ref(yStepSize), std::ref(maxNorm)
};
}
for(size_t i{}; i < threadsNumber; ++i){
threadsVec[i].join();
}
}
关于c++ - 使用线程类在C++中构造线程的动态数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62737701/