unit uPiThread;

interface

uses
Classes;

type
TPiThread = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
end;

var
GlobalPi: Extended;
GlobalCounter: Int64;

implementation

uses uMain;

{ Important: Methods and properties of objects in VCL or CLX can only be used
in a method called using Synchronize, for example,

Synchronize(UpdateCaption);

and UpdateCaption could look like,

procedure TPiThread.UpdateCaption;
begin
Form1.Caption := ‘Updated in a thread’;
end; }

{ TPiThread }

const
//better to choose odd value, to avoid monotonic increase/decrease ef-fect
UpdatePeriod = 999999;

procedure TPiThread.Execute;
var sign: Integer;
PiValue, PrevValue: Extended;
i: Int64;
begin
{ Place thread code here }
PiValue := 4;
sign := -1;
i := 0;
repeat
Inc(i);
PrevValue := PiValue;
PiValue := PiValue + sign * 4 / (2 * i + 1);
sign := -sign;
if i mod UpdatePeriod = 0 then
begin
GlobalPi := PiValue;
GlobalCounter := i;
Synchronize(fmMain.UpdatePi);
end;
until Terminated or
(Abs(PiValue — PrevValue) < 1E-19);
end;

end.
unit uMain;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
uPiThread;

type
TfmMain = class(TForm)
cbCalculate: TCheckBox;
Label1: TLabel;
Label2: TLabel;
laBuiltIn: TLabel;
laValue: TLabel;
laIterNum: TLabel;
procedure FormCreate(Sender: TObject);
procedure cbCalculateClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
PiThread: TPiThread;
procedure UpdatePi;
end;

var
fmMain: TfmMain;

implementation

{$R *.dfm}

procedure TfmMain.UpdatePi;
begin
if IsIconic(Application.Handle) then Exit;
LaValue.Caption := FloatToStrF(GlobalPi, ffFixed, 18, 18);
laIterNum.Caption := IntToStr(GlobalCounter) + ‘ iterations’;
end;

procedure TfmMain.FormCreate(Sender: TObject);
begin
laBuiltIn.Caption := FloatToStrF(Pi, ffFixed, 18, 18);
end;

procedure TfmMain.cbCalculateClick(Sender: TObject);
begin
if cbCalculate.Checked then
begin
PiThread := TPiThread.Create(True);
PiThread.FreeOnTerminate := True;
PiThread.Priority := tpLower;
PiThread.Resume;
end
else
begin
if Assigned(PiThread) then PiThread.Terminate;
end;

end;

end.