title: openmp: race condition in for loop and critical section
body: <p>I'm getting unpredictable errors in my program when running with a lot of threads and am trying to find where the problem sits by inserting critical sections. Now I've got to the following</p>
  <pre class="lang-cpp prettyprint-override"><code>void A::func()
  {
   #pragma omp parallel for
   for (int i=0; i&lt;100; ++i)
    {
      #pragma omp critical
      results[i] = compute(i);
    }
  }
  </code></pre>
  <p>This still gives me the problem that I'm trying to find. The only way I can get it to disappear is by removing the parallelisation of the <code>for</code> loop (not very desirable!).</p>
  <p>Note that the <code>compute</code> function is complicated and actually uses some caches. I wouldn't be surprised if there is some problem in that code, but as the whole thing is now in a critical section, I can't understand what's going on.</p>
  <p>The actual for loop that I'm trying to debug is at <a href="https://github.com/UCL/STIR/blob/49c65340a2116834fea6a9a5cb17f73eb4a6f259/src/scatter_buildblock/ScatterSimulation.cxx#L179-L198" rel="nofollow noreferrer">https://github.com/UCL/STIR/blob/49c65340a2116834fea6a9a5cb17f73eb4a6f259/src/scatter_buildblock/ScatterSimulation.cxx#L179-L198</a>. The test version that still has the problem (close to the example above) is <a href="https://github.com/KrisThielemans/STIR-1/blob/25fe894615534c1f16386b13fd8f231cd3d85673/src/scatter_buildblock/ScatterSimulation.cxx#L179-L194" rel="nofollow noreferrer">here</a></p>
  <p>Note: I had first posted this in a more complicated scenario but I've deleted <a href="https://stackoverflow.com/questions/69600015/openmp-critical-section-inside-a-function-called-in-a-parallel-for-loop">that post</a> as 1) my simple example there doesn't exhibit the problem and 2) this scenario is even more puzzling.</p>
  <p>Some more info added. I'm trying this on Windows 10 with a Ryzen 9 5900. My test code shows occasional problems with gcc-8 and gcc-9 on WSL2/Ubuntu 20.04. (I observe no problems with VS 2019 on windows nor clang-13 on WSL2/Ubuntu 20.04, but that doesn't mean a lot I guess).</p>