title: Occassional thread sync fail after MFC ResumeThread and std::condition_variable wait
body: <p><strong>Background</strong>
  I am finishing up upgrading my MFC framework project from prototype to alpha production code. The task was to synchronize its threads. I used a mixture of mutexes, condition variables and binary semaphores. This has been mostly successful. The stackoverflow case that most resembles my question is <a href="https://stackoverflow.com/questions/33824499/stdcondition-variable-wait-and-notify-one-synchronization">std::condition_variable wait() and notify_one() synchronization</a>.</p>
  <p><strong>Problem</strong>
  Occasionally, though, an atomicity problem occurs after new'ing a certain class derived from CWinThread (RxWs2SocketThread). RxWs2SocketThread switches to the new class'es thread and executes <strong>InitInstance</strong> and switches back again like it is supposed to. In single-threaded programs, when <strong>ResumeThread</strong> is called, the thread switch to InitInstance occurs without problem, but in my multithreaded program, I have to control the switching. Here is the code:</p>
  <p><a href="https://i.stack.imgur.com/aoIUk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aoIUk.png" alt="Thread create and instantiate code" /></a></p>
  <p>The occasional fail occurs between line 95 and 102. Here is the app log showing a successful handoff:</p>
  <p><a href="https://i.stack.imgur.com/X5buv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X5buv.png" alt="successful condition var wait after ResumeThread" /></a></p>
  <p>The number to the left is the thread number. Line numbers are in brackets like [100]. Note that [100] is the instrumentation for the actual <strong>wait</strong> call on line 102. And this app log shows an example of where it fails:</p>
  <p><a href="https://i.stack.imgur.com/exkqs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/exkqs.png" alt="unsuccessful cond var wait" /></a></p>
  <p>In this log, the <strong>notify_one</strong> occurs <em>before</em> the <strong>wait</strong>, which causes the program to hang. Note that line [100] in the app log, which represents the <strong>wait</strong> call in the code on line [102].</p>
  <p><strong>Question</strong>
  This tells me I need to provide atomicity between the <strong>ResumeThread</strong> and <strong>std::condition_variable.wait()</strong> calls. How can I do that? I have to resume the class thread, otherwise the <strong>InitInstance</strong> won't be called, but I can't do a wait after I resume the thread.</p>