title: Fetch-and-add using OpenMP atomic operations
body: <p>I’m using OpenMP and need to use the fetch-and-add operation. However, OpenMP doesn’t provide an appropriate directive/call. I’d like to preserve maximum portability, hence I don’t want to rely on compiler intrinsics.</p>
  
  <p>Rather, I’m searching for a way to harness OpenMP’s atomic operations to implement this but I’ve hit a dead end. Can this even be done? N.B., the following code <em>almost</em> does what I want:</p>
  
  <pre><code>#pragma omp atomic
  x += a
  </code></pre>
  
  <p>Almost – but not quite, since I really need the old value of <code>x</code>. <code>fetch_and_add</code> should be defined to produce the same result as the following (only non-locking):</p>
  
  <pre><code>template &lt;typename T&gt;
  T fetch_and_add(volatile T&amp; value, T increment) {
      T old;
      #pragma omp critical
      {
          old = value;
          value += increment;
      }
      return old;
  }
  </code></pre>
  
  <p>(An equivalent question could be asked for compare-and-swap but one can be implemented in terms of the other, if I’m not mistaken.)</p>