2
votes

Once, during testing, my C++Builder / Delphi application raised an uncaught exception in a background worker thread. EurekaLog caught the exception and sent an error report, as I expected, and everything appeared to be okay.

However, when I closed the application's main window, something remained running in the background, because the application was still listed in the task manager (and still had resources open).

I've tried to duplicate this problem, by deliberately introducing various bugs in the background worker thread, but I can't.

What could cause a thread and application to remain running like this, even after the main window has closed (and, presumably, PostQuitMessage has been called)?

How can I ensure that the application always cleanly shuts down?

2
Do you have any EnterCriticalSection code that could block endlessly? That's a really common deadlock to get right at shutdown, right there.Warren P

2 Answers

7
votes

The first rule is that threads main executor methods should be written so that they can be signalled and shut down properly, and the second rule is that you shouldn't just shut down your app's main thread first, and then hope that the other threads shut down in their own time, to be safe, you should signal all the background threads to stop, wait for that shutdown to complete, and THEN shutdown your main thread. A minimal THREAD example:

procedure TMyThread.Execute;
begin
   Init;
   while not Terminated do
      OneWorkItem; // inside OneWorkItem, you  ALSO need to check for Terminated
end;

A minimal main form/main-thread example:

   procedure TMyMainForm.CheckAndShutdown;
   begin
     if FPendingShutdownFlag then 
       if AllBackgroundThreadsTerminated then 
             Self.Close;
   end;

You could set FPendingShutdownFlag and have the function above called from the application idle processing loop. When you have the user click the main form FormClose, if AllBackgroundThreadsTerminated returns false, set CanClose to false, and set the FPendingShutdownFlag := true instead.

If you make an endless loop (while true), the application does not shut down cleanly, even if it looks like that to you. Somehow, the application is terminated, and the running threads may just suddenly go away quietly, or they may deadlock or otherwise fail on you, as they may be using resources in thread 2 that you are busy freeing in thread 1.

You may have one or more intentional race conditions because you might not have written your thread execute method to be interruptable, or you may start the closing of the main application thread and the VCL and its objects, before you are sure that your background threads are completely shut down.

1
votes

Are you sure that worker thread terminated, and main thread is not waiting for it to finish?