-
Notifications
You must be signed in to change notification settings - Fork 0
/
Threads.pas
99 lines (80 loc) · 2.09 KB
/
Threads.pas
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
unit Threads;
interface
uses
Windows;
type
TThread2 = class;
TThreadProcedure = procedure(Thread: TThread2);
TSynchronizeProcedure = procedure;
TThread2 = class
private
FThreadHandle: longword;
FThreadID: longword;
FExitCode: longword;
FTerminated: boolean;
FExecute: TThreadProcedure;
FData: pointer;
protected
public
constructor Create(ThreadProcedure: TThreadProcedure; CreationFlags: Cardinal);
destructor Destroy; override;
procedure Synchronize(Synchronize: TSynchronizeProcedure);
procedure Lock;
procedure Unlock;
property Terminated: boolean read FTerminated write FTerminated;
property ThreadHandle: longword read FThreadHandle;
property ThreadID: longword read FThreadID;
property ExitCode: longword read FExitCode;
property Data: pointer read FData write FData;
end;
implementation
var
ThreadLock: TRTLCriticalSection;
procedure ThreadWrapper(Thread: TThread2);
var
ExitCode: dword;
begin
Thread.FTerminated := False;
try
Thread.FExecute(Thread);
finally
GetExitCodeThread(Thread.FThreadHandle, ExitCode);
Thread.FExitCode := ExitCode;
Thread.FTerminated := True;
ExitThread(ExitCode);
end;
end;
constructor TThread2.Create(ThreadProcedure: TThreadProcedure; CreationFlags: Cardinal);
begin
inherited Create;
FExitCode := 0;
FExecute := ThreadProcedure;
FThreadHandle := BeginThread(nil, 0, @ThreadWrapper, Pointer(Self), CreationFlags, FThreadID);
end;
destructor TThread2.Destroy;
begin
inherited;
CloseHandle(FThreadHandle);
end;
procedure TThread2.Synchronize(Synchronize: TSynchronizeProcedure);
begin
EnterCriticalSection(ThreadLock);
try
Synchronize;
finally
LeaveCriticalSection(ThreadLock);
end;
end;
procedure TThread2.Lock;
begin
EnterCriticalSection(ThreadLock);
end;
procedure TThread2.Unlock;
begin
LeaveCriticalSection(ThreadLock);
end;
initialization
InitializeCriticalSection(ThreadLock);
finalization
DeleteCriticalSection(ThreadLock);
end.