用线程在c++中相乘多项式

Multiplying polynomials in C++ with threading

本文关键字:多项式 c++ 线程      更新时间:2023-10-16

我试图重写我的一些代码来使用线程,因为我试图在c++中学习它。我有这个方法:

template <typename T>
Polynomial<T> Polynomial<T>::operator *(const Polynomial<T>& other) {
    std::vector<std::future<std::vector<T>>> tempResults;
    for (auto i = 0; i < Coefficients.size(); i++) {
        tempResults.push_back(std::async(std::launch::async, [&other, this](int i) {
            std::vector<T> result(i + other.GetCoefficientsSize() + 2);
            std::fill(result.begin(), result.end(), 0);
            for (auto j = 0; j < other.GetCoefficientsSize(); j++) {
                result.at(j + i + 1) = other.GetCoefficient(j) * Coefficients.at(i);
            }
        return result;
    }, Coefficients.at(i)));
}
std::mutex multiplyMutex;
std::vector<T> total(Coefficients.size() + other.Coefficients.size());
for (auto i = 0; i < tempResults.size(); i++) {
    std::vector<T> result = tempResults.at(i).get();
    std::lock_guard<std::mutex> lock(multiplyMutex);
    for (T value : result) {
        total.at(i) += value;
    }
}
Polynomial<T> result(total);
return result;
经过反复试验,我得到了编译代码。然而,在运行时,我得到一个索引越界异常在这一行:
    std::vector<T> result = tempResults.at(i).get();

此外,逐步调试显示,文件"future"中的某种异常处理也在这一行运行:

   result.at(j + i + 1) = other.GetCoefficient(j) * Coefficients.at(i);

你能识别出发生了什么吗?

我终于自己解决了这个问题。事实证明我犯了一个愚蠢的错误,把异步任务的结果存储在索引Coefficients.at(i)上,这显然是多项式的系数。这反过来又使异步任务的结果超出了tempResults向量的边界。我真正需要的是存储在i

一旦我让它工作,我也发现最后一个for循环是错误的。完整的工作结果如下:

template <typename T>
Polynomial<T> Polynomial<T>::operator *(const Polynomial<T>& other) {
    std::vector<std::future<std::vector<T>>> tempResults; //Results from async will be stored here
    for (int i = 0; i < Coefficients.size(); i++) {
        tempResults.push_back(std::async(std::launch::async, [&other, this](int i) { //Start threads for each Coefficient
            std::vector<T> result(Coefficients.size() + other.GetCoefficientsSize()); //Size of result is the combined degree
            std::fill(result.begin(), result.end(), 0);
            for (auto j = 0; j < other.GetCoefficientsSize(); j++) {
                result.at(i + j + 1) += Coefficients.at(i) * other.GetCoefficient(j);
            }
            return result;
        }, i)); //save in tempResults at i
    }
    std::mutex multiplyMutex;
    std::vector<T> total(Coefficients.size() + other.Coefficients.size());
    for (auto i = 0; i < tempResults.size(); i++) { //Combine tempResults in total
        std::vector<T> result = tempResults.at(i).get(); //Get result of async task
        std::lock_guard<std::mutex> lock(multiplyMutex); //Disallow concurrent access to the final variable
        for (auto j = 0; j < result.size(); j++) {
            total.at(j) += result.at(j);
        }
    }
    Polynomial<T> result(total);
    return result;
}