-
Notifications
You must be signed in to change notification settings - Fork 1
/
threadexample.lpr
129 lines (107 loc) · 2.54 KB
/
threadexample.lpr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
program threadexample;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
Classes, SysUtils, CustApp,
{ you can add units after this }
FPTimer;
type
TCountDownThread = class(TThread)
protected
procedure Execute; override;
public
constructor Create(StartSuspended : boolean);
end;
{ TThreadExample }
TThreadExample = class(TCustomApplication)
protected
FThread : TCountDownThread;
FTimer : TFPTimer;
procedure DoRun; override;
procedure CreateAndStartThread;
procedure OnTimerTick( Sender : TObject);
public
constructor Create(TheOwner : TComponent); override;
destructor Destroy; override;
end;
{ TCountDownThread }
constructor TCountDownThread.Create(StartSuspended : boolean);
begin
FreeOnTerminate := true;
inherited Create(StartSuspended);
end;
procedure TCountDownThread.Execute;
var
WaitSeconds, MaxSeconds, SecondCount : integer;
begin
WaitSeconds := 1;
MaxSeconds := 10;
SecondCount := MaxSeconds;
repeat
WriteLn('Thread: ' + IntToStr(SecondCount));
Sleep(WaitSeconds * 1000);
SecondCount := SecondCount - 1;
until SecondCount = 0;
WriteLn('Thread: ' + IntToStr(SecondCount));
end;
{ TThreadExample }
procedure TThreadExample.DoRun;
var
ErrorMsg : String;
begin
{ add your program heore }
CreateAndStartThread;
FTimer.StartTimer;
while FTimer.Enabled do
begin
WriteLn('Main: waiting...');
CheckSynchronize;
Sleep(500);
end;
// stop program loop
Terminate;
end;
constructor TThreadExample.Create(TheOwner : TComponent);
begin
inherited Create(TheOwner);
StopOnException := True;
FTimer := TFPTimer.Create(self);
FTimer.Enabled := false;
FTimer.Interval := 5000;
FTimer.OnTimer := @OnTimerTick;
end;
destructor TThreadExample.Destroy;
begin
inherited Destroy;
end;
procedure TThreadExample.CreateAndStartThread;
begin
if Assigned(FThread) and (not FThread.Finished) then
raise Exception.Create('Timer: Thread is already running.');
if Assigned(FThread) and FThread.Finished then
FThread := nil;
FThread := TCountDownThread.Create(true);
FThread.Resume;
WriteLn('Timer: Thread started');
end;
procedure TThreadExample.OnTimerTick(Sender : TObject);
begin
WriteLn('--- Tick ---');
try
WriteLn('Timer: trying to start Thread');
CreateAndStartThread;
except
on e : Exception do
WriteLn(e.Message);
end;
end;
var
Application : TThreadExample;
begin
Application := TThreadExample.Create(nil);
Application.Title := 'Thread Example';
Application.Run;
Application.Free;
end.