用线程在c++中相乘多项式
Multiplying polynomials in C++ with threading
我试图重写我的一些代码来使用线程,因为我试图在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;
}
相关文章:
- c++模板来表示多项式
- 使用链表数据结构打印多项式
- 需要帮助重载多项式类运算符C++
- 如何修复此教科书程序以在C++中添加多项式?
- 如何对两个 4 位数字进行乘法,将它们视为 C++ 中的多项式
- 实现伪多项式DP子集和
- 递归程序获得勒让德多项式
- 在 NTL 中构造多项式的标准方法是什么?
- 最小二乘多项式拟合仅适用于偶数个坐标
- 多项式系数代码始终提供相同的答案
- 进入第二个多项式后如何修复分割错误?
- 用霍纳方法进行多项式求值的C++ constexpr
- 卡拉苏巴 - 多项式乘以 CUDA
- 使用链表添加多项式?援助
- 用Isringstream C 提取多项式的系数
- 用于多项式乘法的卡拉苏巴算法
- C :多项式矩阵的输出
- 多项式链接列表中的过载 运算符
- NTRUEncrypt:使用开源标准算法中的描述无法正确找到两个多项式的GCD,无法定义是否存在多边形的逆
- 二阶多项式计算器的输出不一致