title: C swap Pointer Race Conditions
body: <p>Im currently developing a C program which more or less is a unified (de)multiplexer where the user creates a mapping between input and output. While destinations are only held once and are available for all sources, a source can exist once or multiple times in different groups (but not twice in the same group)</p>
  
  <p>Anyhow that is my context. So that groups are useful, I implemented a function that switches the group on user input.</p>
  
  <p>The currently active group is hold by a pointer "activeGroup".</p>
  
  <p>There is a thread for each output destination that waits for input and checks the mapping of the active group, therefore using the "activeGroup" pointer.</p>
  
  <p>My test environment today used ca. 2kHz input, while end-user input could be way higher (like 1000kHz, considering inactive sources can also send data). There were no visible problems.</p>
  
  <p>My question now:</p>
  
  <p>Should I use an RWLock for the "activeGroup" pointer? Is the simple swap of the pointer atomically a problem? Generally I dont mind if one or hundred input packages go to the wrong destination for a brief fraction of a second, but could I somehow have a segmentation fault if the reading threads read in the absolutely wrongest of moments?</p>
  
  <p>the only function that writes to the pointer:</p>
  
  <pre><code>bool activate_group(char *groupName){
      ... (get correct group to activate)
      if(newActive){
          if(activeGroup)
              activeGroup-&gt;isActive = false;
          // the only writing line to activegroup
          activeGroup = grp;
          grp-&gt;isActive = true;
          return true;
      }
      return false;
  }
  </code></pre>
  
  <p>One of the two functions that access it (well pretty similar)</p>
  
  <pre><code>void forward_sender(...){
  
      if(activeGroup &amp;&amp; (input = FINDCORRECTINPUTSOUCEIN(activeGroup-&gt;mappingList)){
  
          snd_params par;
          par.sockfd = sockfd;
          par.msg = buffer;
          par.len = len;
          sendMultipleByInput(activeGroup-&gt;mappingList, sender, &amp;par);
      }
  }
  </code></pre>
  
  <p>The other function sends directly, this one may send multiple times. </p>
  
  <p>If activeGroup switches in between, sendMultipleByInput would simply not send, as it would not find a mapping between the device in the now new active mapping List.</p>
  
  <p>If it could happen with current implementation, would I avoid it by simply accessing the activeGroup pointer once and copying the value into a local pointer?</p>
  
  <p>That would minimize the chance if there is one, I guess?</p>
  
  <p>As performance is the key factor in my program, Id like as much synchronization methods that could slow down or even lead to a deadlock (unlikely using rwlock prefering writer here, but still)</p>
  
  <p>Thanks for any insight</p>