renamed Semaphore to Latch

This commit is contained in:
Michael Schimmel
2025-05-27 11:51:06 +02:00
parent 95fddb0181
commit ca101a3452
7 changed files with 640 additions and 593 deletions
+39 -53
View File
@@ -4,7 +4,7 @@ interface
uses
System.SysUtils, System.Classes, System.SyncObjs,
Myc.Core.Atomic, Myc.Signals;
Myc.Core.Atomic, Myc.Signals; // Myc.Signals now requires direct use of TMycLatch static members
type
IMycTaskFactory = interface
@@ -30,8 +30,8 @@ type
FTerminated: Integer; // Flag to signal worker threads to terminate
[volatile]
FThreadsRunning: Integer; // Counter for active worker threads
FWaitSemaphores: TMycAtomicStack<TSemaphore>; // Pool of semaphores for WaitFor
FWorkGate: TSemaphore; // Semaphore to signal available work to worker threads
FWaitSemaphores: TMycAtomicStack<TSemaphore>; // Pool of System.SyncObjs.TSemaphore for WaitFor
FWorkGate: TSemaphore; // System.SyncObjs.TSemaphore to signal available work
FWorkStack: TMycAtomicStack<TProc>; // Stack of pending jobs
FWorkThreads: TArray<TThread>; // Array of worker threads
procedure WorkerThread;
@@ -76,7 +76,7 @@ type
TMyc2TaskWait = class sealed(TInterfacedObject, IMycSubscriber)
private
[volatile]
FSemaphore: TSemaphore; // Semaphore to be released on notification
FSemaphore: TSemaphore; // System.SyncObjs.TSemaphore to be released on notification
protected
function Notify: Boolean;
@@ -111,16 +111,11 @@ begin
Teardown; // Perform cleanup and stop threads
FWorkGate.Free;
// FException is an acquired exception object, should not be freed manually.
// If FException <> nil here, it means an unhandled exception was not processed by HandleException.
// FException := nil; // Optionally nil it out if necessary for state clarity
inherited Destroy;
end;
class function TMycTaskFactory.CreateAnonymousThread(const DbgName: String; const Proc: TProc): TThread;
{$IFDEF MSWINDOWS}
{$WARN SYMBOL_PLATFORM OFF}
var
prio: TThreadPriority;
{$ENDIF MSWINDOWS}
@@ -128,6 +123,7 @@ begin
Result := TThread.CreateAnonymousThread(Proc);
{$IFDEF MSWINDOWS}
{$WARN SYMBOL_PLATFORM OFF}
// Set priority lower than MainThread priority if created from main thread
if TThread.CurrentThread.ThreadID = MainThreadID then
begin
@@ -137,6 +133,7 @@ begin
Result.Priority := prio;
end;
{$WARN SYMBOL_PLATFORM ON}
{$ENDIF MSWINDOWS}
if DbgName <> '' then
@@ -145,10 +142,11 @@ end;
function TMycTaskFactory.CreateThread(const Proc: TProc): IMycState;
var
res: IMycSemaphore;
res: IMycLatch;
capturedProc: TProc;
begin
res := Signals.CreateSemaphore(1); // Create a semaphore that will be signaled when the proc finishes
// Create a latch that will be signaled when the proc finishes
res := TMycLatch.CreateLatch(1); // Changed to use direct static call on TMycLatch
capturedProc := Proc; // Capture Proc for the anonymous method
CreateAnonymousThread('Thread',
@@ -158,11 +156,12 @@ begin
capturedProc(); // Execute the provided procedure
finally
capturedProc := nil; // Clear the captured proc
res.Notify; // Signal completion
res.Notify; // Signal completion via the latch's Notify method
end;
end).Start;
exit(res.State); // Return the state interface of the semaphore
// Return the state interface of the latch
exit(res.State);
end;
procedure TMycTaskFactory.EnqueueJob(const Job: TProc);
@@ -230,12 +229,12 @@ begin
raise ETaskException.Create('Task factory terminated');
if not Assigned(Job) then
exit(Signals.Null); // Return a null subscriber if no job is provided
exit(TMycLatch.Null); // Already correct, uses direct static property on TMycLatch
if StartCount <= 0 then
begin
EnqueueJob(Job); // Enqueue immediately if no countdown needed
Result := Signals.Null;
Result := TMycLatch.Null; // Already correct
end
else
// Create a pending job that waits for StartCount notifications
@@ -245,34 +244,29 @@ end;
procedure TMycTaskFactory.Teardown;
var
i: Integer;
s: TSemaphore;
job: TProc; // Variable to receive popped job to ensure it's processed/discarded
s: TSemaphore; // This is System.SyncObjs.TSemaphore from FWaitSemaphores
job: TProc;
begin
HandleException; // Process any pending exception before shutdown
if TInterlocked.Exchange(FTerminated, 1) <> 0 then
exit; // Ensure teardown runs only once
// Release the work gate for each thread so they can wake up and terminate
for i := 0 to High(FWorkThreads) do
FWorkGate.Release;
// Wait for all worker threads to finish
TSpinWait.SpinUntil(
function: Boolean
begin
Result := FThreadsRunning = 0;
end);
Assert(FThreadsRunning = 0); // Verify all threads have terminated
Assert(FThreadsRunning = 0);
// Clear any remaining jobs from the work stack (these will not be executed)
repeat
job := FWorkStack.Pop();
until not Assigned(job);
// Clear and free semaphores from the wait semaphore pool
s := FWaitSemaphores.Pop;
while s <> nil do
begin
@@ -283,45 +277,40 @@ end;
procedure TMycTaskFactory.WaitFor(State: IMycState);
var
lock: TSemaphore;
lock: TSemaphore; // This is System.SyncObjs.TSemaphore
begin
// If the state is already set, we are NOT allowed to wait.
if State.IsSet then
exit;
if InWorkerThread then
raise ETaskException.Create('Waiting not allowed within tasks'); // Prevent deadlocks
raise ETaskException.Create('Waiting not allowed within tasks');
lock := FWaitSemaphores.Pop(); // Try to get a semaphore from the pool
lock := FWaitSemaphores.Pop();
if lock = nil then
lock := TSemaphore.Create(nil, 0, 1, ''); // Create new one if pool is empty (initial count 0)
lock := TSemaphore.Create(nil, 0, 1, '');
try
// Subscribe a temporary waiter that will release the lock when the state is signaled
var subscription := State.Subscribe(TMyc2TaskWait.Create(lock));
lock.Acquire; // Wait until the lock is released
lock.Acquire;
finally
// The lock is now signaled (count 0 after Acquire). Push it back to the pool for reuse.
FWaitSemaphores.Push(lock);
end;
HandleException; // Check for exceptions that might have occurred in worker threads during the wait
HandleException;
end;
procedure TMycTaskFactory.ExecuteJob;
var
job: TProc;
begin
job := FWorkStack.Pop(); // Pop a job from the stack
job := FWorkStack.Pop();
if Assigned(job) then
begin
try
job(); // Execute the job
job();
except
// If no exception has been captured yet, capture this one
if FException = nil then
FException := AcquireExceptionObject; // Store the exception object to be raised in the main thread
// Else: an exception is already pending, this one is ignored to keep the first one.
FException := AcquireExceptionObject;
end;
end;
end;
@@ -331,7 +320,7 @@ end;
constructor TMyc2PendingJob.Create(StartCountValue: Integer; OwnerTaskFactory: TMycTaskFactory; const JobProc: TProc);
begin
inherited Create;
Assert(StartCountValue > 0); // StartCount must be positive
Assert(StartCountValue > 0);
FCount := StartCountValue;
FOwner := OwnerTaskFactory;
FJob := JobProc;
@@ -341,42 +330,39 @@ function TMyc2PendingJob.Notify: Boolean;
var
newCount: Integer;
begin
newCount := TInterlocked.Decrement(FCount); // Atomically decrement the counter
// Defend against extreme underflow, though ideally FCount should not go far below zero.
newCount := TInterlocked.Decrement(FCount);
if newCount < -MaxInt div 2 then
TInterlocked.Increment(FCount);
if newCount = 0 then // If counter reaches exactly zero
if newCount = 0 then
begin
// FOwner and FJob are captured by the class instance
if Assigned(FOwner) and Assigned(FJob) then // Ensure owner and job are still valid
if Assigned(FOwner) and Assigned(FJob) then
begin
FOwner.EnqueueJob(FJob); // Enqueue the job
FJob := nil; // Clear the job reference to prevent re-enqueuing and allow ARC
FOwner.EnqueueJob(FJob);
FJob := nil;
end;
end;
Result := newCount > 0; // Returns true if further notifications are expected (count is still positive)
Result := newCount > 0;
end;
{ TMyc2TaskWait }
constructor TMyc2TaskWait.Create(SemaphoreToSignal: TSemaphore);
constructor TMyc2TaskWait.Create(SemaphoreToSignal: TSemaphore); // Parameter is System.SyncObjs.TSemaphore
begin
inherited Create;
FSemaphore := SemaphoreToSignal;
FSemaphore := SemaphoreToSignal; // Field is System.SyncObjs.TSemaphore
end;
function TMyc2TaskWait.Notify: Boolean;
var
s: TSemaphore;
s: TSemaphore; // Local var is System.SyncObjs.TSemaphore
begin
// Atomically exchange FSemaphore with nil to ensure Release is called only once
s := TInterlocked.Exchange<TSemaphore>(FSemaphore, nil);
if s <> nil then
s.Release; // Release the semaphore, unblocking the waiting thread
Result := false; // No further notifications expected from this subscriber
s.Release;
Result := false;
end;
initialization
IsMultiThread := true; // Mark the application as multi-threaded
IsMultiThread := true;
end.