source: trunk/ThreadEx.pas

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
3unit ThreadEx;
4
5interface
6
7uses
8 Classes, SysUtils, SyncObjs, Contnrs;
9
10const
11 Quantum = 10; // ms
12
13type
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
26var
27 ThreadList: TObjectList;
28 ThreadListLock: TCriticalSection;
29
30
31implementation
32
33class function TThreadEx.CurrentThread: TThread;
34var
35 I: Integer;
36begin
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;
50end;
51
52constructor TThreadEx.Create(CreateSuspended: Boolean; const StackSize: SizeUInt
53 );
54begin
55 inherited;
56 try
57 ThreadListLock.Acquire;
58 ThreadList.Add(Self);
59 finally
60 ThreadListLock.Release;
61 end;
62end;
63
64destructor TThreadEx.Destroy;
65begin
66 try
67 ThreadListLock.Acquire;
68 ThreadList.Remove(Self);
69 finally
70 ThreadListLock.Release;
71 end;
72 inherited;
73end;
74
75procedure TThreadEx.Sleep(Delay: Cardinal);
76var
77 I: Integer;
78begin
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;
84end;
85
86initialization
87
88ThreadList := TObjectList.Create;
89ThreadList.OwnsObjects := False;
90ThreadListLock := TCriticalSection.Create;
91
92finalization
93
94ThreadListLock.Free;
95ThreadList.Free;
96
97end.
Note: See TracBrowser for help on using the repository browser.