title: Atomic swap in GNU C++
body: <p>I want to verify that my understanding is correct.  This kind of thing is tricky so I'm almost sure I am missing something.  I have a program consisting of a real-time thread and a non-real-time thread.  I want the non-RT thread to be able to swap a pointer to memory that is used by the RT thread.</p>
  
  <p>From the docs, my understanding is that this can be accomplished in <code>g++</code> with:</p>
  
  <pre><code>// global
  Data *rt_data;
  
  Data *swap_data(Data *new_data)
  {
  #ifdef __GNUC__
      // Atomic pointer swap.
      Data *old_d = __sync_lock_test_and_set(&amp;rt_data, new_data);
  #else
      // Non-atomic, cross your fingers.                                          
      Data *old_d = rt_data;
      rt_data = new_data;
  #endif
      return old_d;
  }
  </code></pre>
  
  <p>This is the only place in the program (other than initial setup) where <code>rt_data</code> is modified.  When <code>rt_data</code> is used in the real-time context, it is copied to a local pointer.  For <code>old_d</code>, later on when it is sure that the old memory is not used, it will be freed in the non-RT thread.  Is this correct? Do I need <code>volatile</code> anywhere?  Are there other synchronization primitives I should be calling?</p>
  
  <p>By the way I am doing this in C++, although I'm interested in whether the answer differs for C.</p>
  
  <p>Thanks ahead of time.</p>