title: Spinlock sync in VC++ without mutex.h
body: <p>I'm kind of lost here.  I believe what I have here is absolutely thread safe, but I'm not sure it is.  I need a very quick spinlock mechanism for small parts of a more complex lock that optimizes thread lock and release (I need to make a larger lock that always releases threads in the order they blocked - something that doesn't happen with mutex/EnterCriticalSection). However - when it comes down to making the smallest and fastest kind of lock possible I'm not really sure what to do.</p>
  
  <pre><code>class SpinGate
  {
  private:
      volatile LONGLONG key = 0;
      volatile LONGLONG gate = 1;
  public:
      void EnterGate();
      void ExitGate();
  };
  
  void SpinGate::EnterGate()
  {
      LONGLONG myKey = InterlockedAdd64(&amp;key, 1);
  
      while (myKey != gate) {}
  }
  
  void SpinGate::ExitGate()
  {
      InterlockedAdd64(&amp;gate, 1);
  }
  </code></pre>
  
  <p>I <em>think</em> this thing I've constructed will ensure that, even if 1,000,000,000 threads try to get a key at the exact same time, they will all get a different key and hence be forced to spin until their key comes up.  But when it comes to C++, the mechanics of implementing safe reads and writes to memory without a standard library object are somewhat beyond the scope of my knowledge.</p>
  
  <p>I'm curious how exactly a function like "interlockedadd64" performs two operations at once, an increment and then a read, while blocking other threads.  And whether or not this is <em>always</em> threadsafe.</p>