CompThread.pas 8.3 KB

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