title: Windows API mutex re-entry issue despite making threads Sleep()
body: <p>I'm trying to get my head around Windows API threads and thread control. I briefly worked with threads in Java so I know the basic concepts but something that has worked in Java seems to only work halfway in C++.</p>
  
  <p>What I am trying to do is as follows: 2 threads in one process, sharing a common resource(for this case, the common resource is a pair of two global variables <code>int a, b;</code>). </p>
  
  <p>The first thread should acquire a mutex, use <code>rand()</code> to generate pairs of numbers from 0 to 100 until it gets a pair such that <code>b == 2 * a</code>, then release the mutex. </p>
  
  <p>The second thread should then acquire the mutex, and check if the <code>b == 2 * a</code> condition is true for the given values(printing something like <code>"incorrect"</code> in case it is not), then release the mutex so the first thread can get it back. This process of generating an checking pairs of numbers should be repeated quite a few times, say 500/1000 times.</p>
  
  <p>My code is as follows:</p>
  
  <p>Main:</p>
  
  <pre><code>#define INIT_SEED               time(NULL)
  #define NUMBER_OF_CHECKS        250
  
  int a = 0;
  int b = 1;
  
  HANDLE mutexHandle = CreateMutex(NULL, FALSE, NULL);
  
  int main()
  {
          HANDLE thread1Handle = CreateThread(NULL, NULL, Thread1Behaviour, NULL, NULL, NULL);
  
          Sleep(50);
  
          HANDLE thread2Handle = CreateThread(NULL, NULL, Thread2Behaviour, NULL, NULL, NULL);
  
          WaitForSingleObject(thread1Handle, INFINITE);
  
          WaitForSingleObject(thread2Handle, INFINITE);
  
          return 0;
  }
  </code></pre>
  
  <p>Thread 1 behavior:</p>
  
  <pre><code>DWORD WINAPI Thread1Behaviour( LPVOID _ )
  {
          srand(INIT_SEED);
  
          for (int i = 0; i &lt; NUMBER_OF_CHECKS; i++)
          { 
                  WaitForSingleObject(mutexHandle, INFINITE);
  
                  do
                  {
                          b = rand() % 100;
                          a = rand() % 100;
                  } 
                  while (b != 2 * a);
  
                  cout &lt;&lt; i &lt;&lt; ".\t" &lt;&lt; b &lt;&lt; " " &lt;&lt; a &lt;&lt; endl;
  
                  ReleaseMutex(mutexHandle);
  
                  Sleep(50);
          }
  
          return 0;
  }
  </code></pre>
  
  <p>Thread 2 behavior:</p>
  
  <pre><code>DWORD WINAPI Thread2Behaviour( LPVOID _ )
  {
          for (int i = 0; i &lt; NUMBER_OF_CHECKS; i++)
          {
                  WaitForSingleObject(mutexHandle, INFINITE);
  
                  if (b == 2 * a)
                          cout &lt;&lt; i &lt;&lt; ".\t" &lt;&lt; b &lt;&lt; "\t=\t2 * " &lt;&lt; a &lt;&lt; endl;
                  else
                          cout &lt;&lt; i &lt;&lt; ".\t" &lt;&lt; b &lt;&lt; "\t=\t2 * " &lt;&lt; a &lt;&lt; "\tINCORRECT!!!" &lt;&lt; endl;
  
                  ReleaseMutex(mutexHandle);
  
                  Sleep(50);
          }
  
          return 0;
  }
  </code></pre>
  
  <p>The implementation is simple enough(I skipped over the handle validity checks to keep the code short, in case a bad handle could be the cause i can add them in, but I imagine that in case of a bad handle everything should just crash &amp; burn, not work but with incorrect outputs).</p>
  
  <p>I remember for working with threads in Java that i used to sleep for some time to make sure the same thread does not reacquire the mutex. However, when I run the above code, it mainly works as intended however, when the number of checks is big enough, somethimes the first thread gets the mutex 2 times in a row, leading to an output like this:</p>
  
  <pre><code>1.      92 46
  2.      66 33
  1.      66      =       2 * 33
  </code></pre>
  
  <p>Which means that at the end, the second thread will end up checking the same pair several times:</p>
  
  <pre><code>249.    80 40
  248.    80      =       2 * 40
  249.    80      =       2 * 40
  </code></pre>
  
  <p>I have tried changing the sleep timer value with values between 0 and 250 but this remains the case no matter how large the sleep period is. When I put at least 250 it seems to work about half the time.</p>
  
  <p>Also, if I remove the cout in the first thread, the problem becomes 2-3 times worse, with more botched synchronizations.</p>
  
  <p>And one more thing I noticed is that for a certain configuration of sleep timer and cout/no cout in thread 1, the number of times the mutex is immediately reacquired is the same, so this is completely reproducible(at least for me). </p>
  
  <p>Using logic, I got 2 conflicting conclusions:</p>
  
  <ol>
  <li><p>Since it MOSTLY works as intended, it might be a synchronization problem, with the way threads "rush" for the mutex as soon as it is available</p></li>
  <li><p>Since I am able to reproduce this issue in a pretty "deterministic" way, it might mean that it is an issue in the logic of the code </p></li>
  </ol>
  
  <p>But the above can't both be true at once, so what exactly is the problem here?</p>
  
  <p>EDIT: To clarify the question: I know that mutex is not technically used for order of execution, but in this case, why does it not work as intended and what would be the fix?</p>
  
  <p>Thanks in advance!  </p>