What could cause a C++Builder / Delphi thread and application to not shut down?-Collection of common programming errors
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.