source: branches/DirectWeb/UResetableThread.pas

Last change on this file was 89, checked in by george, 14 years ago
  • Opraveno: Chybné vytváření pojmenovaných objektů TEvent.
  • Opraveno: Chybné přidělování a uvolňování zásobníků vláken a databázových spojení.
  • Opraveno: Chybná inicializace parametrů databázových spojení.
File size: 1.9 KB
Line 
1unit UResetableThread;
2
3{$mode Delphi}{$H+}
4
5interface
6
7uses
8 Classes, SysUtils, syncobjs;
9
10type
11 TResetableThread = class;
12
13 { TResetableThreadExecute }
14
15 TResetableThreadExecute = class(TThread)
16 Parent: TResetableThread;
17 procedure Execute; override;
18 end;
19
20 { TResetableThread }
21
22 TResetableThread = class
23 private
24 StartEvent: TEvent;
25 StopEvent: TEvent;
26 public
27 Thread: TResetableThreadExecute;
28 Stopped: Boolean;
29 procedure Execute; virtual; abstract;
30 procedure Stop;
31 procedure Start;
32 procedure WaitForStart;
33 procedure WaitForStop;
34 constructor Create;
35 destructor Destroy; override;
36 end;
37
38implementation
39
40{ TResetableThread }
41
42procedure TResetableThread.Stop;
43begin
44 Stopped := True;
45end;
46
47procedure TResetableThread.Start;
48begin
49 if Stopped then StartEvent.SetEvent;
50end;
51
52procedure TResetableThread.WaitForStart;
53var
54 WaitResult: TWaitResult;
55begin
56 repeat
57 WaitResult := StartEvent.WaitFor(1000);
58 until WaitResult <> wrTimeout;
59 if WaitResult = wrError then
60 raise Exception.Create('WaitFor error');
61end;
62
63procedure TResetableThread.WaitForStop;
64begin
65 while StopEvent.WaitFor(1000) = wrTimeout do ;
66end;
67
68constructor TResetableThread.Create;
69begin
70 Stopped := True;
71 StartEvent := TEvent.Create(nil, False, False, '');
72 StopEvent := TEvent.Create(nil, False, False, '');
73 Thread := TResetableThreadExecute.Create(True);
74 Thread.Parent := Self;
75 Thread.Resume;
76end;
77
78destructor TResetableThread.Destroy;
79begin
80 Stop;
81 WaitForStop;
82 Thread.Destroy;
83 StartEvent.Destroy;
84 StopEvent.Destroy;
85 inherited Destroy;
86end;
87
88{ TResetableThreadExecute }
89
90procedure TResetableThreadExecute.Execute;
91begin
92 while not Terminated do begin
93 Parent.WaitForStart;
94 Parent.Stopped := False;
95 Parent.Execute;
96 Parent.Stopped := True;
97 Parent.StopEvent.SetEvent;
98 end;
99end;
100
101end.
102
Note: See TracBrowser for help on using the repository browser.