并行和顺序运行代码时会产生不同的结果
Different results when running code in parallel and sequentially
当我运行代码时,我得到不同的结果。我想在不同线程中同时更改矢量的不同单元格。当线程多于单元格时会发生错误(是的,我知道在这种情况下并行化不是最佳选择,但我想了解为什么结果不同(。
它不起作用
w[i] -= speed * derivative[i];
它有效
w[i] = w[i] - speed * derivative[i];
所有代码
#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <iomanip>
#include <omp.h>
#include "windows.h"
using namespace std;
class neuron
{
public:
neuron() //constructor with starting filling for example
{
w.resize(3);
w[0] = 0.7700484068199707;
w[1] = 0.3427844318371112;
w[2] = 0.6822299620512033;
derivative.resize(3);
derivative[0] = 0.232342234223;
derivative[1] = 0.23232232234223;
derivative[2] = 0.23234334231113;
}
void correction_of_scales(const double& speed)
{
#pragma omp parallel for num_threads(8) //threads more than cells
for (size_t i = 0; i < w.size(); ++i)
{
#pragma omp atomic
w[i] -= speed * derivative[i]; //here is here is happening what the magic
//w[i] = w[i] - speed * derivative[i]; - and here it works without errors
}
}
vector <double> derivative;
vector <double> w;
};
int main(void)
{
neuron nn;
for (int i = 0; i < 100; i++) //a hundred times in a row change the vector
nn.correction_of_scales(0.01);
for (int i = 0; i < nn.w.size(); i++)
cout << scientific << setprecision(15) << nn.w[i] << endl;
system("pause");
}
这是按顺序运行它时出现的内容
5.377061725969665e-01
1.104621094948808e-01
4.498866197400767e-01
但是并行运行时会发生什么
-6.24004998518318e-01
1.104621094948808e-01
4.498866197400767e-01
这是Visual Studio的一个例外developercommunity.visualstudio.com
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- CMake-按正确顺序将项目与C运行时对象文件链接
- 函数调用中参数的顺序重要吗
- 为什么不;名字在地图上是按顺序排列的吗
- 用C++20 fmt限制结果的总大小
- 对象指针打印结果以相反的顺序进行
- 并行和顺序运行代码时会产生不同的结果
- 当变量的顺序发生变化时C++双倍乘法会产生不同的结果
- 来自Sprintf的弦乐的结果与在Ubuntu Server上传递的参数ODER具有不同的值顺序
- 将主机字节顺序转换为网络字节顺序有时会导致奇怪的结果
- 为什么 bool 显示正确的位顺序,而直接输出移位运算结果却不显示?
- 为什么cout以相反的顺序给我一个结果
- 顺序和并行版本给出不同的结果 - 为什么
- 如何在 std::vector 中查找重复项<strings>并返回一个 std::list 它们按字母顺序排序,在该结果列表中没有重复项
- 循环结果按顺序排列
- OpenCV 3.1 + tesseract 3.04的OCR(文本识别)结果根据识别的顺序而变化
- 改变继承顺序会产生不同的结果
- 为了得到最精确的结果,应该按哪个顺序添加浮点数
- 如何将排序函数应用于字符串.find( ) 以按字母顺序打印结果