Advertisement
FlyFar

abThreads.pas

Dec 19th, 2023
1,267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 2.07 KB | Cybersecurity | 0 0
  1. unit abThreads;
  2.  
  3. interface
  4.   uses Windows;
  5.  
  6. type
  7.   TThread = class;
  8.   TThreadProcedure = procedure(Thread: TThread);
  9.   TSynchronizeProcedure = procedure;
  10.   TThread = class
  11.   private
  12.     FThreadHandle: longword;
  13.     FThreadID: longword;
  14.     FExitCode: longword;
  15.     FTerminated: boolean;
  16.     FExecute: TThreadProcedure;
  17.     FData: pointer;
  18.   protected
  19.   public
  20.     constructor Create(ThreadProcedure: TThreadProcedure; CreationFlags: Cardinal);
  21.     destructor Destroy; override;
  22.     procedure Synchronize(Synchronize: TSynchronizeProcedure);
  23.     procedure Lock;
  24.     procedure Unlock;
  25.     property Terminated: Boolean read FTerminated write FTerminated;
  26.     property ThreadHandle: LongWord read FThreadHandle;
  27.     property ThreadID: LongWord read FThreadID;
  28.     property ExitCode: LongWord read FExitCode;
  29.     property Data: Pointer read FData write FData;
  30.   end;
  31.  
  32. implementation
  33.  
  34. var
  35.   ThreadLock: TRTLCriticalSection;
  36.  
  37. procedure ThreadWrapper(Thread: TThread);
  38. var
  39.   ExitCode: dword;
  40. begin
  41.   Thread.FTerminated := False;
  42.   try
  43.     Thread.FExecute(Thread);
  44.   finally
  45.     GetExitCodeThread(Thread.FThreadHandle, ExitCode);
  46.     Thread.FExitCode := ExitCode;
  47.     Thread.FTerminated := True;
  48.     ExitThread(ExitCode);
  49.   end;
  50. end;
  51.  
  52. constructor TThread.Create(ThreadProcedure: TThreadProcedure; CreationFlags: Cardinal);
  53. begin
  54.   inherited Create;
  55.   FExitCode := 0;
  56.   FExecute := ThreadProcedure;
  57.   FThreadHandle := BeginThread(nil, 0, @ThreadWrapper, Pointer(Self), CreationFlags, FThreadID);
  58. end;
  59.  
  60. destructor TThread.Destroy;
  61. begin
  62.   inherited;
  63.   CloseHandle(FThreadHandle);
  64. end;
  65.  
  66. procedure TThread.Synchronize(Synchronize: TSynchronizeProcedure);
  67. begin
  68.   EnterCriticalSection(ThreadLock);
  69.   try
  70.     Synchronize;
  71.   finally
  72.     LeaveCriticalSection(ThreadLock);
  73.   end;
  74. end;
  75.  
  76. procedure TThread.Lock;
  77. begin
  78.   EnterCriticalSection(ThreadLock);
  79. end;
  80.  
  81. procedure TThread.Unlock;
  82. begin
  83.   LeaveCriticalSection(ThreadLock);
  84. end;
  85.  
  86. initialization
  87.   InitializeCriticalSection(ThreadLock);
  88.  
  89. finalization
  90.   DeleteCriticalSection(ThreadLock);
  91.  
  92. end.
  93.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement