title: Atomically read/write int value w/o additional operation on the int value itself
body: <p>GCC offers a nice set of <a href="http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html">built-in functions</a> for atomic operations. And being on MacOS or iOS, even Apple offers a <a href="http://developer.apple.com/library/mac/#documentation/Darwin/Reference/KernelIOKitFramework/OSAtomic_h/index.html">nice set of atomic functions</a>. However, all these functions perform an operation, e.g. an addition/subtraction, a logical operation (AND/OR/XOR) or a compare-and-set/compare-and-swap. What I am looking for is a way to atomically assign/read an <code>int</code> value, like:</p>
  
  <pre><code>int a;
  /* ... */    
  a = someVariable;
  </code></pre>
  
  <p>That's all. <code>a</code> will be read by another thread and it is only important that <code>a</code> either has its old value or its new value. Unfortunately the C standard does not guarantee that assigning or reading a value is an atomic operation. I remember that I once read somewhere, that writing or reading a value to a variable of type <code>int</code> is guaranteed to be atomic in GCC (regardless the size of int) but I searched everywhere on the GCC homepage and I cannot find this statement any longer (maybe it was removed).</p>
  
  <p>I cannot use <code>sig_atomic_t</code> because sig_atomic_t has no guaranteed size and it might also have a different size than <code>int</code>.</p>
  
  <p>Since only one thread will ever "write" a value to <code>a</code>, while both threads will "read" the current value of <code>a</code>, I don't need to perform the operations themselves in an atomic manner, e.g.:</p>
  
  <pre><code>/* thread 1 */
  someVariable = atomicRead(a);
  /* Do something with someVariable, non-atomic, when done */
  atomicWrite(a, someVariable);
  
  /* thread 2 */
  someVariable = atomicRead(a);
  /* Do something with someVariable, but never write to a */
  </code></pre>
  
  <p>If both threads were going to write to <code>a</code>, then all operations would have to be atomic, but that way, this may only waste CPU time; and we are extremely low on CPU resources in our project. So far we use a mutex around read/write operations of <code>a</code> and even though the mutex is held for such a tiny amount of time, this already causes problems (one of the threads is a realtime thread and blocking on a mutex causes it to fail its realtime constraints, which is pretty bad).</p>
  
  <p>Of course I could use a <code>__sync_fetch_and_add</code> to read the variable (and simply add "0" to it, to not modify its value) and for writing use a <code>__sync_val_compare_and_swap</code> for writing it (as I know its old value, so passing that in will make sure the value is always exchanged), but won't this add unnecessary overhead?</p>