运行代码时,我得到不同的结果。我想同时在不同线程中更改向量的不同单元格。当线程数多于单元数时发生错误(是的,我知道在这种情况下并行化不是最佳选择,但我想了解为什么结果不同)。
不起作用
Design
有效
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