title: openMP - concurrent access to variables and atomic
body: <p>I want to parallelize with openMP a function that is sampling a box (selecting points randomly in a box, and evaluating a given function at these points). I wrote the following code. </p>
  
  <pre><code>//storing points
  double** points_ = new double*[N-m];
  for(int i=0;i&lt;N-m;i++)
  {
      points_[i]=new double[ndim];
  }
  double* evals_ = new double[N-m];
  
  #pragma omp parallel for 
  for(int i=0;i&lt;N-m;i++)
  {
      double* pt_ = randomPoint(lower,upper);
      for(int k=0;k&lt;ndim;k++)
      {
          points_[i][k]=pt_[k];
      }
      evals_[i]=evalFunc(pt_);
      delete pt_;
  }
  </code></pre>
  
  <p>However, I am not confident with this code: evals_ and points_ are updated in eauch thread. I think of adding some atomic statements there: </p>
  
  <pre><code>#pragma omp parallel for 
  for(int i=0;i&lt;N-m;i++)
  {
      double* pt_ = randomPoint(m_lower,m_upper);
      for(int k=0;k&lt;m_ndim;k++)
      {
          #pragma omp atomic update
          points_[i][k]=pt_[k];
      }
      #pragma omp atomic update
      evals_[i]=evalFunc(pt_);
      delete pt_;
  }
  </code></pre>
  
  <p>but I fear that this would be very unefficient: do you have some advice to write it more accurately? And... this is not compiling... (error: expression following #pragma omp atomic has improper form) althought I can find that examlpe in openMP specs, A22 </p>
  
  <pre><code>void atomic_example(float *x, float *y, int *index, int n)
  {
      int i;
      #pragma omp parallel for shared(x, y, index, n)
      for (i=0; i&lt;n; i++) {
      #pragma omp atomic update
      x[index[i]] += work1(i);
      y[i] += work2(i);
      }
  }
  </code></pre>
  
  <p>and atomic update is also followed here by an affectation to an array.</p>
  
  <p>Thanks and regards.</p>
  
  <p>EDIT--------</p>
  
  <p>I agree with Tudor's answer. However, it seems that this example here, in another parallelized piece of code does need atomic: on line sum_+=..., an error occurs (concurrent access)</p>
  
  <pre><code>for(i=0;i&lt;m_ndim;i++)
  {
      double sum_=0;
      #pragma omp parallel reduction(+:sum_)
      for(j=0;j&lt;m_npts;j++)
      {
          sum_ += set_[j][i];
      }
      Sum_[i] = sum_;
  }
  </code></pre>
  
  <p>Why is it then needed? Or is smthing else wrong?</p>