Ed.C
Ed.C

Reputation: 798

Calling a function from a function pointer in Delphi

I'm trying to build a generic worker thread in Delphi, one that I can pass a function/procedure (doesn't matter) as an argument and let it execute.

My guess is to add a field in the TThread class and call it from TThread.Execute.

So the code outside the thread is gonna be:

  MyThread := TWorkerThread.Create(True);
  Mythread.CallBackF := @Foo;
  try
    MyThread.Resume;
  except
    MyThread.Free;
  end;

How do I keep a reference of @foo in the TWorkerThread and call it from inside Execute?

Upvotes: 4

Views: 1816

Answers (3)

Alex
Alex

Reputation: 5668

Take a look at QueueUserWorkItem function.

It executes arbitrary function in a thread, without requiring you to create one. Just don't forget to switch IsMultithreaded global variable to True.

Upvotes: 4

skamradt
skamradt

Reputation: 15538

Also, a good start into using generic threads would be AsyncCalls or Omni Thread Library.

Upvotes: 6

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108963

I do not pretend to be an expert on threading, but I think this will do it:

interface

    type
      TProcRef = reference to procedure;
      TWorkerThread = class(TThread)
      public
        proc: TProcRef;
        procedure Execute; override;
        class procedure RunInThread(AProc: TProcRef);
      end;

implementation

procedure TWorkerThread.Execute;
begin
  inherited;
  proc;
end;

class procedure TWorkerThread.RunInThread(AProc: TProcRef);
begin
  with TWorkerThread.Create(true) do
  begin
    FreeOnTerminate := true;
    proc := AProc;
    Resume;
  end;
end;    

Then, if you got any procedure, like

procedure P;
begin
  while true do
  begin
    sleep(1000);
    beep;
  end;
end;

you can just do

procedure TForm1.Button1Click(Sender: TObject);
begin
  TWorkerThread.RunInThread(P);
end;

You can even do

TWorkerThread.RunInThread(procedure begin while true do begin sleep(1000); beep; end; end);

Upvotes: 5

Related Questions