c++ - 使用线程类在C++中构造线程的动态数组时出错

标签 c++ multithreading c++11 pointers dynamic

作为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)
对于本质上不合适的函数模板,此代码仍然无法正常工作,并给出相同的编译器错误(C2672C2893),就好像我没有传递正确的参数类型一样。您能弄清楚代码有什么问题吗?

最佳答案

使用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/

相关文章:

c++ - 核心文件完全是胡说八道,或者这段代码真的会引发 SIGFPE 吗?

c++ - 将 std::thread 与 std::mutex 一起使用

ios - Swift:使用 NSLock 或并发队列的安全线程

java - Thread中List的内存范围

c++ - 保留 std::initializer_list 的拷贝是否安全?这是什么道理?

python - SWIG 添加行以删除不存在的变量

c++ - 在 C++ 中使用 startMATLAB 并在 r2017b 中使用 "MatlabEngine.hpp"时发出问题

c++ - google::dense_hash_map 与 boost::unordered_map 性能问题

c++ - 有什么方法可以编译时检查字符串用户定义的文字吗?

c++ - 为什么枚举不能用作此 vector 构造函数中的参数?