title: Leaving critical section after thread crash
body: <p>I've got thread executing commands from list</p>
  
  <pre><code>do
  {
      commandExec-&gt;criticalSection.EnterCS();
      if (!commandExec-&gt;commands.empty())
      {
          commandExec-&gt;ExecuteCommand(commandExec-&gt;commands.front());
          commandExec-&gt;commands.pop_front();
      }
      else
          commandExec-&gt;criticalSection.SuspendThread();
      commandExec-&gt;criticalSection.LeaveCS();
  } while (commandExec-&gt;maintainCommandExecution);
  </code></pre>
  
  <p>and second thread which adds commands to list:</p>
  
  <pre><code>criticalSection.EnterCS();
  commands.push_back(Command(code, parameters));
  criticalSection.LeaveCS();
  criticalSection.ResumeThread();
  </code></pre>
  
  <p>First thread could crash while executing command, therefore critical section could not be accessed by second thread:</p>
  
  <blockquote>
    <p>If a thread terminates while it has ownership of a critical section, the state of the critical section is undefined.
    <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms682608%28v=vs.85%29.aspx" rel="nofollow">Source</a></p>
  </blockquote>
  
  <p><strong>So, what's the good way to handle this problem?</strong> 
  I could think of some solutions, but they seems tricky (adding third thread, second critical section, etc.)</p>
  
  <p>(criticalSection it's just simple wrapper for CRITICAL_SECTION)</p>