CompThread.pas 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. unit CompThread;
  2. interface
  3. {$WARN SYMBOL_DEPRECATED OFF}
  4. {$WARN SYMBOL_PLATFORM OFF}
  5. uses
  6. Classes, Windows;
  7. type
  8. { TCompThread }
  9. TCompThread = class
  10. private
  11. FHandle: THandle;
  12. FThreadID: TThreadID;
  13. FTerminated: Boolean;
  14. FSuspended: Boolean;
  15. FFreeOnTerminate: Boolean;
  16. FFinished: Boolean;
  17. FReturnValue: Integer;
  18. FOnTerminate: TNotifyEvent;
  19. FMethod: TThreadMethod;
  20. FSynchronizeException: TObject;
  21. procedure CallOnTerminate;
  22. function GetPriority: TThreadPriority;
  23. procedure SetPriority(Value: TThreadPriority);
  24. procedure SetSuspended(Value: Boolean);
  25. protected
  26. procedure DoTerminate; virtual;
  27. procedure Execute; virtual; abstract;
  28. procedure Synchronize(Method: TThreadMethod);
  29. property ReturnValue: Integer read FReturnValue write FReturnValue;
  30. property Terminated: Boolean read FTerminated;
  31. public
  32. constructor Create(CreateSuspended: Boolean);
  33. destructor Destroy; override;
  34. procedure Resume;
  35. procedure Suspend;
  36. procedure Terminate; virtual;
  37. function WaitFor(Milliseconds: Cardinal = INFINITE): Boolean;
  38. property FreeOnTerminate: Boolean read FFreeOnTerminate write FFreeOnTerminate;
  39. property Handle: THandle read FHandle;
  40. property Priority: TThreadPriority read GetPriority write SetPriority;
  41. property Suspended: Boolean read FSuspended write SetSuspended;
  42. property ThreadID: TThreadID read FThreadID;
  43. property OnTerminate: TNotifyEvent read FOnTerminate write FOnTerminate;
  44. end;
  45. implementation
  46. uses
  47. SysUtils, DateUtils;
  48. const
  49. CM_EXECPROC = $8FFF;
  50. CM_DESTROYWINDOW = $8FFE;
  51. type
  52. PRaiseFrame = ^TRaiseFrame;
  53. TRaiseFrame = record
  54. NextRaise: PRaiseFrame;
  55. ExceptAddr: Pointer;
  56. ExceptObject: TObject;
  57. ExceptionRecord: PExceptionRecord;
  58. end;
  59. var
  60. ThreadLock: TRTLCriticalSection;
  61. ThreadWindow: HWND;
  62. ThreadCount: Integer;
  63. procedure FreeThreadWindow;
  64. begin
  65. if ThreadWindow <> 0 then
  66. begin
  67. DestroyWindow(ThreadWindow);
  68. ThreadWindow := 0;
  69. end;
  70. end;
  71. function ThreadWndProc(Window: HWND; Message, wParam, lParam: Longint): Longint; stdcall;
  72. begin
  73. case Message of
  74. CM_EXECPROC:
  75. with TCompThread(lParam) do
  76. begin
  77. Result := 0;
  78. try
  79. FSynchronizeException := nil;
  80. FMethod;
  81. except
  82. FSynchronizeException := AcquireExceptionObject;
  83. end;
  84. end;
  85. CM_DESTROYWINDOW:
  86. begin
  87. EnterCriticalSection(ThreadLock);
  88. try
  89. Dec(ThreadCount);
  90. if ThreadCount = 0 then
  91. FreeThreadWindow;
  92. finally
  93. LeaveCriticalSection(ThreadLock);
  94. end;
  95. Result := 0;
  96. end;
  97. else
  98. Result := DefWindowProc(Window, Message, wParam, lParam);
  99. end;
  100. end;
  101. var
  102. ThreadWindowClass: TWndClass = (
  103. style: 0;
  104. lpfnWndProc: @ThreadWndProc;
  105. cbClsExtra: 0;
  106. cbWndExtra: 0;
  107. hInstance: 0;
  108. hIcon: 0;
  109. hCursor: 0;
  110. hbrBackground: 0;
  111. lpszMenuName: nil;
  112. lpszClassName: 'TThreadWindow');
  113. procedure AddThread;
  114. function AllocateWindow: HWND;
  115. var
  116. TempClass: TWndClass;
  117. ClassRegistered: Boolean;
  118. begin
  119. ThreadWindowClass.hInstance := HInstance;
  120. ClassRegistered := GetClassInfo(HInstance, ThreadWindowClass.lpszClassName,
  121. TempClass);
  122. if not ClassRegistered or (TempClass.lpfnWndProc <> @ThreadWndProc) then
  123. begin
  124. if ClassRegistered then
  125. Windows.UnregisterClass(ThreadWindowClass.lpszClassName, HInstance);
  126. Windows.RegisterClass(ThreadWindowClass);
  127. end;
  128. Result := CreateWindow(ThreadWindowClass.lpszClassName, '', 0,
  129. 0, 0, 0, 0, 0, 0, HInstance, nil);
  130. end;
  131. begin
  132. EnterCriticalSection(ThreadLock);
  133. try
  134. if ThreadCount = 0 then
  135. ThreadWindow := AllocateWindow;
  136. Inc(ThreadCount);
  137. finally
  138. LeaveCriticalSection(ThreadLock);
  139. end;
  140. end;
  141. procedure RemoveThread;
  142. begin
  143. EnterCriticalSection(ThreadLock);
  144. try
  145. if ThreadCount = 1 then
  146. PostMessage(ThreadWindow, CM_DESTROYWINDOW, 0, 0);
  147. finally
  148. LeaveCriticalSection(ThreadLock);
  149. end;
  150. end;
  151. {type
  152. PThreadRec = ^TThreadRec;
  153. TThreadRec = record
  154. Func: TThreadFunc;
  155. Parameter: Pointer;
  156. end;
  157. function ThreadWrapper(Parameter: Pointer): Integer; stdcall;
  158. asm
  159. CALL _FpuInit
  160. XOR ECX,ECX
  161. PUSH EBP
  162. PUSH offset _ExceptionHandler
  163. MOV EDX,FS:[ECX]
  164. PUSH EDX
  165. MOV EAX,Parameter
  166. MOV FS:[ECX],ESP
  167. MOV ECX,[EAX].TThreadRec.Parameter
  168. MOV EDX,[EAX].TThreadRec.Func
  169. PUSH ECX
  170. PUSH EDX
  171. CALL _FreeMem
  172. POP EDX
  173. POP EAX
  174. CALL EDX
  175. XOR EDX,EDX
  176. POP ECX
  177. MOV FS:[EDX],ECX
  178. POP ECX
  179. POP EBP
  180. end;
  181. function BeginThread(SecurityAttributes: Pointer; StackSize: LongWord;
  182. ThreadFunc: TThreadFunc; Parameter: Pointer; CreationFlags: LongWord;
  183. var ThreadId: LongWord): Integer;
  184. var
  185. P: PThreadRec;
  186. begin
  187. New(P);
  188. P.Func := ThreadFunc;
  189. P.Parameter := Parameter;
  190. IsMultiThread := TRUE;
  191. Result := CreateThread(SecurityAttributes, StackSize, @ThreadWrapper, P,
  192. CreationFlags, ThreadID);
  193. end;
  194. procedure EndThread(ExitCode: Integer);
  195. begin
  196. ExitThread(ExitCode);
  197. end;
  198. }
  199. { TCompThread }
  200. function ThreadProc(Thread: TCompThread): Integer;
  201. var
  202. FreeThread: Boolean;
  203. begin
  204. try
  205. Thread.Execute;
  206. finally
  207. FreeThread := Thread.FFreeOnTerminate;
  208. Result := Thread.FReturnValue;
  209. Thread.FFinished := True;
  210. Thread.DoTerminate;
  211. if FreeThread then
  212. begin
  213. Thread.Free;
  214. end;
  215. EndThread(Result);
  216. // it should not get past EndThread
  217. end;
  218. end;
  219. constructor TCompThread.Create(CreateSuspended: Boolean);
  220. var
  221. Flags: Cardinal; //DWORD;
  222. begin
  223. inherited Create;
  224. AddThread;
  225. FSuspended := CreateSuspended;
  226. Flags := 0;
  227. if CreateSuspended then Flags := CREATE_SUSPENDED;
  228. FHandle := BeginThread(nil, 0, @ThreadProc, Pointer(Self), Flags, FThreadID);
  229. end;
  230. destructor TCompThread.Destroy;
  231. begin
  232. if not FFinished and not Suspended then
  233. begin
  234. Terminate;
  235. WaitFor;
  236. end;
  237. if FHandle <> 0 then CloseHandle(FHandle);
  238. inherited Destroy;
  239. RemoveThread;
  240. end;
  241. procedure TCompThread.CallOnTerminate;
  242. begin
  243. if Assigned(FOnTerminate) then FOnTerminate(Self);
  244. end;
  245. procedure TCompThread.DoTerminate;
  246. begin
  247. if Assigned(FOnTerminate) then Synchronize(CallOnTerminate);
  248. end;
  249. const
  250. Priorities: array [TThreadPriority] of Integer =
  251. (THREAD_PRIORITY_IDLE, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL,
  252. THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL,
  253. THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_TIME_CRITICAL);
  254. function TCompThread.GetPriority: TThreadPriority;
  255. var
  256. P: Integer;
  257. I: TThreadPriority;
  258. begin
  259. P := GetThreadPriority(FHandle);
  260. Result := tpNormal;
  261. for I := Low(TThreadPriority) to High(TThreadPriority) do
  262. if Priorities[I] = P then Result := I;
  263. end;
  264. procedure TCompThread.SetPriority(Value: TThreadPriority);
  265. begin
  266. SetThreadPriority(FHandle, Priorities[Value]);
  267. end;
  268. procedure TCompThread.Synchronize(Method: TThreadMethod);
  269. begin
  270. FSynchronizeException := nil;
  271. FMethod := Method;
  272. SendMessage(ThreadWindow, CM_EXECPROC, 0, Longint(Self));
  273. if Assigned(FSynchronizeException) then raise FSynchronizeException;
  274. end;
  275. procedure TCompThread.SetSuspended(Value: Boolean);
  276. begin
  277. if Value <> FSuspended then
  278. if Value then
  279. Suspend else
  280. Resume;
  281. end;
  282. procedure TCompThread.Suspend;
  283. begin
  284. FSuspended := True;
  285. SuspendThread(FHandle);
  286. end;
  287. procedure TCompThread.Resume;
  288. begin
  289. if ResumeThread(FHandle) = 1 then FSuspended := False;
  290. end;
  291. procedure TCompThread.Terminate;
  292. begin
  293. FTerminated := True;
  294. end;
  295. function TCompThread.WaitFor(Milliseconds: Cardinal): Boolean;
  296. var
  297. Msg: TMsg;
  298. H: THandle;
  299. Start: TDateTime;
  300. R: DWORD;
  301. begin
  302. H := FHandle;
  303. if GetCurrentThreadID = MainThreadID then
  304. begin
  305. Start := Now;
  306. repeat
  307. R := MsgWaitForMultipleObjects(1, H, False, Milliseconds, QS_SENDMESSAGE);
  308. if R = WAIT_OBJECT_0 + 1 then PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE)
  309. until (R <> WAIT_OBJECT_0 + 1) or ((Milliseconds <> INFINITE) and (MilliSecondsBetween(Now, Start) >= Milliseconds));
  310. end
  311. else
  312. begin
  313. R := WaitForSingleObject(H, Milliseconds);
  314. end;
  315. Result := (R = WAIT_OBJECT_0);
  316. end;
  317. initialization
  318. InitializeCriticalSection(ThreadLock);
  319. finalization
  320. DeleteCriticalSection(ThreadLock);
  321. end.