title: Delphi Multi-Threading Message Loop
body: <p>My application has several threads:
  1) Main Thread
  2) 2 Sub-Main Threads (each with Message Loop, as shown below), used by TFQM
  3) n Worker Threads (simple loop, containing Sleep())</p>
  
  <p>My problem is, when I close my application, the Worker Threads manage to exit properly, but 1 of the 2 Sub-Main Threads hangs (never exits) when I issue WM_QUIT to close them.</p>
  
  <hr>
  
  <pre><code>procedure ThreadProcFQM(P: Integer); stdcall;
  var
    Msg: TMsg;
   _FQM: TFQM;
  begin
    _FQM := Ptr(P);
    try
      _FQM.fHandle := AllocateHwnd(_FQM.WndProc);
  
      while GetMessage(Msg, 0, 0, 0) do
      begin
        TranslateMessage(Msg);
        DispatchMessage(Msg);
      end;
  
    finally
      DeallocateHWnd(_FQM.fHandle);
      SetEvent(_FQM.hTerminated);
    end;
  end;
  </code></pre>
  
  <hr>
  
  <pre><code>procedure TFQM.Stop;
  begin
    PostMessage(fHandle, WM_QUIT, 0, 0);
  
    WaitForSingleObject(hTerminated, INFINITE);
    if hThread &lt;&gt; INVALID_HANDLE_VALUE then
    begin
      CloseHandle(hThread);
      hThread := INVALID_HANDLE_VALUE;
    end;
  end;
  </code></pre>