title: Waiting until another process locks and then unlocks a Win32 mutex
body: <p>I am trying to tell when a producer process accesses a shared windows mutex. After this happens, I need to lock that same mutex and process the associated data. Is there a build in way in Windows to do this, short of a ridiculous loop?</p>
  
  <p>I know the result of this is doable through creating a custom Windows event in the producer process, but I want to avoid changing this programs code as much as possible.</p>
  
  <p>What I believe will work (in a ridiculously inefficient way) would be this (NOTE: this is not my real code, I know there are like 10 different things very wrong with this; I want to avoid doing anything like this):</p>
  
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;Windows.h&gt;
  
  int main() {
      HANDLE h = CreateMutex(NULL, 0, "name");
      if(!h) return -1;
  
      int locked = 0;
      while(true) {
          if(locked) {
              //can assume it wont be locked longer than a second, but even if it does should work fine
              if(WaitForSingleObject(h, 1000) == WAIT_OBJECT_0) {
                  // do processing...
                  locked = 0;
                  ReleaseMutex(h);
              }
          // oh god this is ugly, and wastes so much CPU...
          } else if(!(locked = WaitForSingleObject(h, 0) == WAIT_TIMEOUT)) {
              ReleaseMutex(h);
          }
      }
      return 0;
  }
  </code></pre>
  
  <p>If there is an easier way with C++ for whatever reason, my code is actually that. This example was just easier to construct in C.</p>