title: Interlocked read on readonly memory page triggers access violation
body: <p>In order to perform interlocked reads I have used <code>InterlockedCompareExchange</code> function a la</p>
  
  <pre><code>value = InterlockedCompareExchange(ptr, 0, 0);
  </code></pre>
  
  <p>Now I stumbled upon unusual situation. 
  <br>I want to use this interlocked "read" on a <strong>read-only</strong> (write-protected) memory page. The result is <strong>"Access violation writing location x"</strong>... </p>
  
  <p>So I guess this is by design? I understand that <code>InterlockedCompareExchange</code> is often a used as a "write" instruction. But why is access violation trigger included in this particular case?</p>
  
  <p>What are the alternatives to <code>InterlockedCompareExchange</code> in order to perform interlocked read?</p>
  
  <p><br><strong>Update:</strong> I tried using </p>
  
  <pre><code>value = InterlockedCompareExchange(ptr, 0, -1);
  </code></pre>
  
  <p>when I know that the value at <em>ptr</em> is never negative, but this triggers the access violation also, even though in this case there certainly isn't any writing going on. So I guess this is by design with this instruction... 
  <br>But why and how to get around that?</p>
  
  <p><br><strong>Update2:</strong> More details about why I started using interlocked reads.
  <br>I left my question intentionally vague. I am generally interested in the topic, that is - both skipping the cache and having atomic reads, including atomic 64-bit reads.</p>
  
  <p>The reason why I started wondering is that <strong>.NET</strong> uses <code>CompareExchange</code> for interlocked reading inside <br><code>System.Threading.Interlocked.Read(ref Int64 location)</code> <br>method.
  <br>The MSDN states for this .NET <code>Interlocked.Read</code> method: <strong>"The Read method is unnecessary on 64-bit systems, because 64-bit read operations are already atomic. On 32-bit systems, 64-bit read operations are not atomic unless performed using Read."</strong></p>
  
  <p>Also, MSDN states for (C-language) <code>InterlockedCompareExchange64</code> function that unaligned operations are not permitted in any case: <strong>"The variables for this function must be aligned on a 64-bit boundary; otherwise, this function will behave unpredictably on multiprocessor x86 systems and any non-x86 systems"</strong>. 
  <br>So according to that text also .NET should never have unaligned Int64 variables. But then why interlocked reading?</p>