Last change
on this file was 60, checked in by chronos, 4 weeks ago |
- Modified: Remove U prefix from unit names.
|
File size:
1.7 KB
|
Line | |
---|
1 | // Date: 2011-02-01
|
---|
2 |
|
---|
3 | unit ThreadEx;
|
---|
4 |
|
---|
5 | interface
|
---|
6 |
|
---|
7 | uses
|
---|
8 | Classes, SysUtils, SyncObjs, Contnrs;
|
---|
9 |
|
---|
10 | const
|
---|
11 | Quantum = 10; // ms
|
---|
12 |
|
---|
13 | type
|
---|
14 |
|
---|
15 | { TThreadEx }
|
---|
16 |
|
---|
17 | TThreadEx = class(TThread)
|
---|
18 | public
|
---|
19 | constructor Create(CreateSuspended: Boolean;
|
---|
20 | const StackSize: SizeUInt = DefaultStackSize);
|
---|
21 | destructor Destroy; override;
|
---|
22 | procedure Sleep(Delay: Cardinal);
|
---|
23 | class function CurrentThread: TThread;
|
---|
24 | end;
|
---|
25 |
|
---|
26 | var
|
---|
27 | ThreadList: TObjectList;
|
---|
28 | ThreadListLock: TCriticalSection;
|
---|
29 |
|
---|
30 |
|
---|
31 | implementation
|
---|
32 |
|
---|
33 | class function TThreadEx.CurrentThread: TThread;
|
---|
34 | var
|
---|
35 | I: Integer;
|
---|
36 | begin
|
---|
37 | try
|
---|
38 | ThreadListLock.Acquire;
|
---|
39 | if MainThreadID = GetThreadId then Result := nil
|
---|
40 | else begin
|
---|
41 | I := 0;
|
---|
42 | while (I < ThreadList.Count) and (TThread(ThreadList[I]).ThreadID <> GetThreadID) do
|
---|
43 | Inc(I);
|
---|
44 | if I < ThreadList.Count then Result := TThread(ThreadList[I])
|
---|
45 | else Result := nil;
|
---|
46 | end;
|
---|
47 | finally
|
---|
48 | ThreadListLock.Release;
|
---|
49 | end;
|
---|
50 | end;
|
---|
51 |
|
---|
52 | constructor TThreadEx.Create(CreateSuspended: Boolean; const StackSize: SizeUInt
|
---|
53 | );
|
---|
54 | begin
|
---|
55 | inherited;
|
---|
56 | try
|
---|
57 | ThreadListLock.Acquire;
|
---|
58 | ThreadList.Add(Self);
|
---|
59 | finally
|
---|
60 | ThreadListLock.Release;
|
---|
61 | end;
|
---|
62 | end;
|
---|
63 |
|
---|
64 | destructor TThreadEx.Destroy;
|
---|
65 | begin
|
---|
66 | try
|
---|
67 | ThreadListLock.Acquire;
|
---|
68 | ThreadList.Remove(Self);
|
---|
69 | finally
|
---|
70 | ThreadListLock.Release;
|
---|
71 | end;
|
---|
72 | inherited;
|
---|
73 | end;
|
---|
74 |
|
---|
75 | procedure TThreadEx.Sleep(Delay: Cardinal);
|
---|
76 | var
|
---|
77 | I: Integer;
|
---|
78 | begin
|
---|
79 | SysUtils.Sleep(Delay mod Quantum);
|
---|
80 | for I := 1 to (Delay div Quantum) do begin
|
---|
81 | if Terminated then Break;
|
---|
82 | SysUtils.Sleep(Quantum);
|
---|
83 | end;
|
---|
84 | end;
|
---|
85 |
|
---|
86 | initialization
|
---|
87 |
|
---|
88 | ThreadList := TObjectList.Create;
|
---|
89 | ThreadList.OwnsObjects := False;
|
---|
90 | ThreadListLock := TCriticalSection.Create;
|
---|
91 |
|
---|
92 | finalization
|
---|
93 |
|
---|
94 | ThreadListLock.Free;
|
---|
95 | ThreadList.Free;
|
---|
96 |
|
---|
97 | end.
|
---|
Note:
See
TracBrowser
for help on using the repository browser.