Is there a way to use FreeOnTerminate other that setting it in the constructor (or before the thread starts / or in the rather complex manner below)?

The doc does not mention any limitations https://www.freepascal.org/docs-html/rtl/classes/tthread.freeonterminate.html

However, setting FreeOnTerminate*after* Execute() has finished has no effect.

So code like:

  t := TThread.create(false); // create  not suspended
  // do something
  if foo then begin // decide we do not need the result
    t.FreeOnTerminate:= true;
    t.terminate;
 end;


This may fail. If the thread's execute already finished, then the thread is not destroyed. The code cannot call WaitFor, because the thread could still be running for a long time. And even take a long time until it recognizes the "terminate" request.
So the app wants just to signal it, and tell it to clean up after itself.

But in the above code, if Execute() had already finished, t is never destroyed. (tested with 3.0.4)

One would have to test for Finished in addition. Only that Finished could change between it being queried and any subsequent action.
So the only solution I can see is maybe

  t := TThread.create(false); // create  not suspended
   // do something
   if foo then begin // decide we do not need the result
    t.Suspend;
    if t.Finished then begin
      t.free; // Not sure, since it is finished, we would not need to 
Terminate, WaitFor  or Resume ?
      t := nil;
    end
    else begin
      t.FreeOnTerminate:= true;
      t.terminate;
      t.Resume;
      t := nil; // no longer save to access
   end;
  end;


1) Is there an easier way?
2) Should the doc have any hint towards this?
3) Should FreeOnTerminate maybe detect this situation itself?

_______________________________________________
fpc-pascal maillist  -  fpc-pascal@lists.freepascal.org
http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

Reply via email to