CompThread.pas 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. if RaiseList <> nil then
  83. begin
  84. FSynchronizeException := PRaiseFrame(RaiseList)^.ExceptObject;
  85. PRaiseFrame(RaiseList)^.ExceptObject := nil;
  86. end;
  87. end;
  88. end;
  89. CM_DESTROYWINDOW:
  90. begin
  91. EnterCriticalSection(ThreadLock);
  92. try
  93. Dec(ThreadCount);
  94. if ThreadCount = 0 then
  95. FreeThreadWindow;
  96. finally
  97. LeaveCriticalSection(ThreadLock);
  98. end;
  99. Result := 0;
  100. end;
  101. else
  102. Result := DefWindowProc(Window, Message, wParam, lParam);
  103. end;
  104. end;
  105. var
  106. ThreadWindowClass: TWndClass = (
  107. style: 0;
  108. lpfnWndProc: @ThreadWndProc;
  109. cbClsExtra: 0;
  110. cbWndExtra: 0;
  111. hInstance: 0;
  112. hIcon: 0;
  113. hCursor: 0;
  114. hbrBackground: 0;
  115. lpszMenuName: nil;
  116. lpszClassName: 'TThreadWindow');
  117. procedure AddThread;
  118. function AllocateWindow: HWND;
  119. var
  120. TempClass: TWndClass;
  121. ClassRegistered: Boolean;
  122. begin
  123. ThreadWindowClass.hInstance := HInstance;
  124. ClassRegistered := GetClassInfo(HInstance, ThreadWindowClass.lpszClassName,
  125. TempClass);
  126. if not ClassRegistered or (TempClass.lpfnWndProc <> @ThreadWndProc) then
  127. begin
  128. if ClassRegistered then
  129. Windows.UnregisterClass(ThreadWindowClass.lpszClassName, HInstance);
  130. Windows.RegisterClass(ThreadWindowClass);
  131. end;
  132. Result := CreateWindow(ThreadWindowClass.lpszClassName, '', 0,
  133. 0, 0, 0, 0, 0, 0, HInstance, nil);
  134. end;
  135. begin
  136. EnterCriticalSection(ThreadLock);
  137. try
  138. if ThreadCount = 0 then
  139. ThreadWindow := AllocateWindow;
  140. Inc(ThreadCount);
  141. finally
  142. LeaveCriticalSection(ThreadLock);
  143. end;
  144. end;
  145. procedure RemoveThread;
  146. begin
  147. EnterCriticalSection(ThreadLock);
  148. try
  149. if ThreadCount = 1 then
  150. PostMessage(ThreadWindow, CM_DESTROYWINDOW, 0, 0);
  151. finally
  152. LeaveCriticalSection(ThreadLock);
  153. end;
  154. end;
  155. {type
  156. PThreadRec = ^TThreadRec;
  157. TThreadRec = record
  158. Func: TThreadFunc;
  159. Parameter: Pointer;
  160. end;
  161. function ThreadWrapper(Parameter: Pointer): Integer; stdcall;
  162. asm
  163. CALL _FpuInit
  164. XOR ECX,ECX
  165. PUSH EBP
  166. PUSH offset _ExceptionHandler
  167. MOV EDX,FS:[ECX]
  168. PUSH EDX
  169. MOV EAX,Parameter
  170. MOV FS:[ECX],ESP
  171. MOV ECX,[EAX].TThreadRec.Parameter
  172. MOV EDX,[EAX].TThreadRec.Func
  173. PUSH ECX
  174. PUSH EDX
  175. CALL _FreeMem
  176. POP EDX
  177. POP EAX
  178. CALL EDX
  179. XOR EDX,EDX
  180. POP ECX
  181. MOV FS:[EDX],ECX
  182. POP ECX
  183. POP EBP
  184. end;
  185. function BeginThread(SecurityAttributes: Pointer; StackSize: LongWord;
  186. ThreadFunc: TThreadFunc; Parameter: Pointer; CreationFlags: LongWord;
  187. var ThreadId: LongWord): Integer;
  188. var
  189. P: PThreadRec;
  190. begin
  191. New(P);
  192. P.Func := ThreadFunc;
  193. P.Parameter := Parameter;
  194. IsMultiThread := TRUE;
  195. Result := CreateThread(SecurityAttributes, StackSize, @ThreadWrapper, P,
  196. CreationFlags, ThreadID);
  197. end;
  198. procedure EndThread(ExitCode: Integer);
  199. begin
  200. ExitThread(ExitCode);
  201. end;
  202. }
  203. { TCompThread }
  204. function ThreadProc(Thread: TCompThread): Integer;
  205. var
  206. FreeThread: Boolean;
  207. begin
  208. try
  209. Thread.Execute;
  210. finally
  211. FreeThread := Thread.FFreeOnTerminate;
  212. Result := Thread.FReturnValue;
  213. Thread.FFinished := True;
  214. Thread.DoTerminate;
  215. if FreeThread then
  216. begin
  217. Thread.Free;
  218. end;
  219. EndThread(Result);
  220. // it should not get past EndThread
  221. end;
  222. end;
  223. constructor TCompThread.Create(CreateSuspended: Boolean);
  224. var
  225. Flags: Cardinal; //DWORD;
  226. begin
  227. inherited Create;
  228. AddThread;
  229. FSuspended := CreateSuspended;
  230. Flags := 0;
  231. if CreateSuspended then Flags := CREATE_SUSPENDED;
  232. FHandle := BeginThread(nil, 0, @ThreadProc, Pointer(Self), Flags, FThreadID);
  233. end;
  234. destructor TCompThread.Destroy;
  235. begin
  236. if not FFinished and not Suspended then
  237. begin
  238. Terminate;
  239. WaitFor;
  240. end;
  241. if FHandle <> 0 then CloseHandle(FHandle);
  242. inherited Destroy;
  243. RemoveThread;
  244. end;
  245. procedure TCompThread.CallOnTerminate;
  246. begin
  247. if Assigned(FOnTerminate) then FOnTerminate(Self);
  248. end;
  249. procedure TCompThread.DoTerminate;
  250. begin
  251. if Assigned(FOnTerminate) then Synchronize(CallOnTerminate);
  252. end;
  253. const
  254. Priorities: array [TThreadPriority] of Integer =
  255. (THREAD_PRIORITY_IDLE, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL,
  256. THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL,
  257. THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_TIME_CRITICAL);
  258. function TCompThread.GetPriority: TThreadPriority;
  259. var
  260. P: Integer;
  261. I: TThreadPriority;
  262. begin
  263. P := GetThreadPriority(FHandle);
  264. Result := tpNormal;
  265. for I := Low(TThreadPriority) to High(TThreadPriority) do
  266. if Priorities[I] = P then Result := I;
  267. end;
  268. procedure TCompThread.SetPriority(Value: TThreadPriority);
  269. begin
  270. SetThreadPriority(FHandle, Priorities[Value]);
  271. end;
  272. procedure TCompThread.Synchronize(Method: TThreadMethod);
  273. begin
  274. FSynchronizeException := nil;
  275. FMethod := Method;
  276. SendMessage(ThreadWindow, CM_EXECPROC, 0, Longint(Self));
  277. if Assigned(FSynchronizeException) then raise FSynchronizeException;
  278. end;
  279. procedure TCompThread.SetSuspended(Value: Boolean);
  280. begin
  281. if Value <> FSuspended then
  282. if Value then
  283. Suspend else
  284. Resume;
  285. end;
  286. procedure TCompThread.Suspend;
  287. begin
  288. FSuspended := True;
  289. SuspendThread(FHandle);
  290. end;
  291. procedure TCompThread.Resume;
  292. begin
  293. if ResumeThread(FHandle) = 1 then FSuspended := False;
  294. end;
  295. procedure TCompThread.Terminate;
  296. begin
  297. FTerminated := True;
  298. end;
  299. function TCompThread.WaitFor(Milliseconds: Cardinal): Boolean;
  300. var
  301. Msg: TMsg;
  302. H: THandle;
  303. Start: TDateTime;
  304. R: DWORD;
  305. begin
  306. H := FHandle;
  307. if GetCurrentThreadID = MainThreadID then
  308. begin
  309. Start := Now;
  310. repeat
  311. R := MsgWaitForMultipleObjects(1, H, False, Milliseconds, QS_SENDMESSAGE);
  312. if R = WAIT_OBJECT_0 + 1 then PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE)
  313. until (R <> WAIT_OBJECT_0 + 1) or ((Milliseconds <> INFINITE) and (MilliSecondsBetween(Now, Start) >= Milliseconds));
  314. end
  315. else
  316. begin
  317. R := WaitForSingleObject(H, Milliseconds);
  318. end;
  319. Result := (R = WAIT_OBJECT_0);
  320. end;
  321. initialization
  322. InitializeCriticalSection(ThreadLock);
  323. finalization
  324. DeleteCriticalSection(ThreadLock);
  325. end.