[fpc-pascal] TThread.Queue vs TThread.Synchronize

Sven Barth pascaldragon at googlemail.com
Mon Feb 23 19:23:12 CET 2015


On 23.02.2015 18:58, Graeme Geldenhuys wrote:
> Continuing on the TThread.Queue subject - is there any way to pass
> parameters (or record structure with basic types) to the Queue() call?
>
> That would be super useful instead of putting thread locking on
> variables (for example, reading a progress value to update a GUI
> progress bar).

Currently the only method is to use fields that belong to the TThread 
instance.

> I understand that anonymous methods (something I again don't know much
> about) take a snapshot of local variables. So that could possibly be
> used with TThread.Queue() to send variable (simple data types)
> information? Please correct my if I am wrong - like I said, I don't
> really know anonymous methods or their real usage.

In Delphi both TThread.Queue() and TThread.Synchronize() have overloads 
to accept anonymous functions. It would then work like this:

=== code begin ===

type
   TPrintEvent = procedure(const aMsg: String) of object;

   TMyThread = class(TThread)
   private
     fOnPrint: TPrintEvent;
   protected
     procedure Execute; override;
     property OnPrint: TPrintEvent read fOnPrint write fOnPrint;
   end;

procedure TMyThread.Execute;
var
   s: String;
begin
   s := 'Hello World';
   Queue(procedure
     begin
       fOnPrint(s);
     end);
end;

=== code end ===

In this example both "fOnPrint" and "s" would be captured by the 
anonymous functions and will be available even after the thread has 
terminated.

For FPC modes and those people that dislike the syntax of anonymous 
functions (and yes, I can understand those people ;) ) I hope that we'll 
get the following variation to work as well:

=== code begin ===

procedure TMyThread.Execute;
var
   s: String;

   procedure SyncOnPrint;
   begin
     fOnPrint(s);
   end;

begin
   s := 'Hello World';
   Queue(@SyncOnPrint);
end;

=== code end ===

Regards,
Sven



More information about the fpc-pascal mailing list