[Lazarus] Event created by program logic rather than user action
Anthony Walter
sysrpl at gmail.com
Sun Nov 8 18:33:42 CET 2015
Here's an example which calculates Pi forever in a thread. It's important
to note a few things:
1. Periodically check if the thread should stop by checking the Terminated
property inside Execute
2. If you want to communicate with the user interface, such as refreshing
the screen based on some calculations, use the Synchronize method to do so
3. Do not share data the thread is using in calculations with anything. If
you need access to the data in somewhere else, use Synchronize and make a
copy there.
unit Main;
{$mode delphi}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
{ TMainForm }
type
TMainForm = class(TForm)
OutputLabel: TLabel;
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
private
FThread: TThread;
end;
var
MainForm: TMainForm;
implementation
{$R *.lfm}
{ TCalculatePiThread }
type
TCalculatePiThread = class(TThread)
private
FPiDigits: string;
protected
procedure Update;
procedure Execute; override;
end;
procedure TCalculatePiThread.Update;
begin
MainForm.OutputLabel.Caption := FPiDigits;
end;
procedure TCalculatePiThread.Execute;
var
Data: array[0..2801] of Integer;
I, K, B, D, C: Integer;
begin
FreeOnTerminate := True;
while not Terminated do
begin
C := 0;
for I := Low(Data) to High(Data) do
Data[I] := 2800;
K := 2800;
while K > 0 do
begin
K := K - 14;
D := 0;
I := K;
while not Terminated do
begin
D := D + Data[I] * 10000;
B := 2 * I - 1;
Data[I] := D mod B;
D := D div B;
Dec(I);
if I < 1 then
Break;
D := D * I;
end;
FPiDigits := Format('%.4d', [C + D div 10000]);
Synchronize(Update);
C := D mod 10000;
end;
end;
end;
{ TMainForm }
procedure TMainForm.FormCreate(Sender: TObject);
begin
FThread := TCalculatePiThread.Create(False);
end;
procedure TMainForm.FormClose(Sender: TObject; var CloseAction:
TCloseAction);
begin
FThread.Terminate;
end;
end.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lazarus-ide.org/pipermail/lazarus/attachments/20151108/0e13252c/attachment-0003.html>
More information about the Lazarus
mailing list