Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I terminate my threads with blocking functions/procedures?

I use TThread in my application and I have a LOT of functions that I would like to use inside of it. Functions that I use, take time to complete, so it's not ideal to use them in threads. That's why I was wondering if there's a way other than just copy & paste the function/procedure and then put (maybe inject) my terminated flags into the function. I don't want to use TerminateThread API!

A short example:

procedure MyProcedure;
begin
 // some work that takes time over a few lines of code
 // add/inject terminated flag?!
 // try... finally...
end;

procedure TMyThread.Execute;
begin
 MyProcedure;
 // or copy and paste myprocedure
end;

So is there an efficient way to write procedures/functions that help me with the terminated flag? Also the procedures/functions should be global so other functions/procedures can call them too.

like image 481
Ben Avatar asked Dec 26 '22 20:12

Ben


1 Answers

One option is to introduce a callback method into your procedure call. If the callback method is Assigned (when called from a thread) make the call and take action.

When calling MyProcedure from elsewhere, pass nil to the procedure.

Type
  TAbortProc = function : boolean of object;

procedure MyProcedure( AbortProc : TAbortProc);
begin
  //...
  if (Assigned(AbortProc) and AbortProc) then
    Exit;
  //...
end;


function MyThread.AbortOperation : Boolean;
begin
  Result := Terminated;
end;

The reason why I avoid passing the thread reference instead of a callback method, is to hide the thread logic (and dependency) from MyProcedure.

like image 104
LU RD Avatar answered May 10 '23 23:05

LU RD