title: Two Different Processes With 2 std::atomic Variables on Same Address?
body: <p>I read C++ Standard (n4713)'s § 32.6.1 3:</p>
  
  <blockquote>
    <p>Operations that are lock-free should also be address-free. That is,
    atomic operations on the same memory location via two different
    addresses will communicate atomically. The implementation should not
    depend on any per-process state. This restriction enables
    communication by memory that is mapped into a process more than once
    and by memory that is shared between two processes.</p>
  </blockquote>
  
  <p>So it sounds like it is possible to perform a lock-free atomic operation on the same memory location.  I wonder how it can be done.</p>
  
  <p>Let's say I have a named shared memory segment on Linux (via shm_open() and mmap()).  How can I perform a lockfree operation on the first 4 bytes of the shared memory segment for example?</p>
  
  <p>At first, I thought I could just <code>reinterpret_cast</code> the pointer to <code>std::atomic&lt;int32_t&gt;*</code>.  But then I read <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4013.html" rel="nofollow noreferrer">this</a>.  It first points out that std::atomic might not have the same size of T or alignment:</p>
  
  <blockquote>
    <p>When we designed the C++11 atomics, I was under the misimpression that
    it would be possible  to semi-portably apply atomic operations to data
    not declared to be atomic, using  code such as</p>
  </blockquote>
  
  <pre><code>int x; reinterpret_cast&lt;atomic&lt;int&gt;&amp;&gt;(x).fetch_add(1);
  </code></pre>
  
  <blockquote>
    <p>This would clearly fail if the representations of atomic and int
    differ, or if their alignments differ. But I know that this is not an
    issue on platforms I care about. And, in practice, I can easily test
    for a problem by checking at compile time that sizes and alignments
    match.</p>
  </blockquote>
  
  <p>Tho, it is fine with me in this case because I use a shared memory on the same machine and casting the pointer in two different processes will "acquire" the same location.  However, the article states that the compiler might not treat the casted pointer as a pointer to an atomic type:</p>
  
  <blockquote>
    <p>However this is not guaranteed to be reliable, even on platforms on
    which one  might expect it to work, since it may confuse type-based
    alias analysis in the  compiler. A compiler may assume that an int is
    not also accessed as an <code>atomic&lt;int&gt;</code>. (See 3.10, [Basic.lval], last
    paragraph.)</p>
  </blockquote>
  
  <p>Any input is welcome!</p>