TaskFactory added
This commit is contained in:
+22
-15
@@ -56,6 +56,8 @@ type
|
||||
// Pushes an item onto the stack.
|
||||
procedure Push(const Data: T); inline;
|
||||
|
||||
procedure Clear;
|
||||
|
||||
// Allocates an aligned memory block for a stack item.
|
||||
function Alloc: PItem; inline;
|
||||
// Pushes a pre-allocated item pointer onto the SList.
|
||||
@@ -183,22 +185,8 @@ begin
|
||||
end;
|
||||
|
||||
class operator TMycAtomicStack<T>.Finalize(var Dest: TMycAtomicStack<T>);
|
||||
var
|
||||
item: PItem;
|
||||
begin
|
||||
// Use Dest to access fields and call instance methods
|
||||
// on the record instance being finalized
|
||||
item := Dest.PopPtr; // Call instance method PopPtr via Dest
|
||||
while item <> nil do
|
||||
begin
|
||||
item.Data := Default(T);
|
||||
FreeMemAligned(item); // Global procedure
|
||||
item := Dest.PopPtr; // Call instance method PopPtr via Dest
|
||||
end;
|
||||
if Dest.FSList <> nil then // Check if FSList was initialized
|
||||
begin
|
||||
Dest.FSList.Free; // Call instance method Free on FSList via Dest
|
||||
end;
|
||||
Dest.Clear;
|
||||
end;
|
||||
|
||||
function TMycAtomicStack<T>.Alloc: PItem;
|
||||
@@ -209,6 +197,25 @@ begin
|
||||
Result.Data := Default(T);
|
||||
end;
|
||||
|
||||
procedure TMycAtomicStack<T>.Clear;
|
||||
var
|
||||
item: PItem;
|
||||
begin
|
||||
// Use Dest to access fields and call instance methods
|
||||
// on the record instance being finalized
|
||||
item := PopPtr; // Call instance method PopPtr via Dest
|
||||
while item <> nil do
|
||||
begin
|
||||
item.Data := Default(T);
|
||||
FreeMemAligned(item); // Global procedure
|
||||
item := PopPtr; // Call instance method PopPtr via Dest
|
||||
end;
|
||||
if FSList <> nil then // Check if FSList was initialized
|
||||
begin
|
||||
FSList.Free; // Call instance method Free on FSList via Dest
|
||||
end;
|
||||
end;
|
||||
|
||||
function TMycAtomicStack<T>.Pop: T;
|
||||
begin
|
||||
// Instance method
|
||||
|
||||
+46
-69
@@ -1,49 +1,47 @@
|
||||
unit Myc.Core.Notifier;
|
||||
|
||||
interface
|
||||
|
||||
uses
|
||||
System.SysUtils, System.SyncObjs;
|
||||
|
||||
type
|
||||
// Low-level implementation for thread-safe multicast events.
|
||||
// Implemented as a list referencing IInterface instances, with a locking mechanism for thread safety.
|
||||
// Utilizes minimal memory.
|
||||
// `Advise` adds an interface and returns a tag for constant-time removal by `Unadvise`.
|
||||
// `UnadviseAll` removes all registered interfaces.
|
||||
// After `Finalize` is called, the list is cleared, and no new interfaces can be added (closed state).
|
||||
TMycNotifyList<T: IInterface> = record
|
||||
type
|
||||
TTag = Pointer; // Opaque tag used to identify a registered receiver for unsubscription.
|
||||
|
||||
PItem = ^TItem; // Pointer to an internal list item.
|
||||
TItem = record // Internal structure for storing a receiver and list linkage.
|
||||
Next, Prev: PItem; // Pointers to the next and previous items in the doubly linked list.
|
||||
Receiver: T; // The registered interface instance (the event sink).
|
||||
end;
|
||||
|
||||
strict private
|
||||
FFirst: NativeUInt; // Stores the first receiver if no list is allocated, or acts as a combined lock and state field.
|
||||
// Bit 0: Lock state (0 = locked, 1 = unlocked).
|
||||
// Bit 1: Finalized state (0 = not finalized, 1 = finalized).
|
||||
// Other bits (if not 0 and bit 0 is 1) can be a direct interface pointer if FList is nil.
|
||||
FList: PItem; // Head of the linked list for additional receivers beyond the first one.
|
||||
|
||||
class function AllocItem: PItem; static; inline; // Allocates and initializes memory for a new TItem.
|
||||
class procedure FreeItem( Item: PItem ); static; inline; // Frees memory previously allocated for a TItem.
|
||||
|
||||
public
|
||||
procedure Create; // Initializes the notification list, preparing it for use.
|
||||
procedure Destroy; // Cleans up all resources, including unadvising all receivers. Assumes no concurrent access.
|
||||
function Advise(const Receiver: T): TTag; // Registers a receiver interface and returns an opaque tag for later unsubscription.
|
||||
procedure Unadvise(Tag: TTag); // Unregisters a specific receiver using the tag obtained from Advise.
|
||||
procedure UnadviseAll; // Unregisters all currently advised receivers.
|
||||
procedure Finalize; // Clears all receivers and permanently prevents new interfaces from being added.
|
||||
procedure Lock; inline; // Acquires an exclusive lock for thread-safe operations on the list.
|
||||
procedure Release; inline;// Releases the previously acquired exclusive lock.
|
||||
function IsLocked: Boolean; inline; // Checks if the list is currently locked by any thread.
|
||||
function IsFinalized: Boolean; inline; // Checks if the list has been finalized and no longer accepts new receivers.
|
||||
procedure Notify(Func: TPredicate<T>); // Iterates through registered receivers and invokes the predicate; removes receiver if predicate returns false.
|
||||
|
||||
interface
|
||||
|
||||
uses
|
||||
System.SysUtils, System.SyncObjs;
|
||||
|
||||
type
|
||||
// Low-level implementation for thread-safe multicast events.
|
||||
// Implemented as a list referencing IInterface instances, with a locking mechanism for thread safety.
|
||||
// Utilizes minimal memory.
|
||||
// `Advise` adds an interface and returns a tag for constant-time removal by `Unadvise`.
|
||||
// `UnadviseAll` removes all registered interfaces.
|
||||
// After `Finalize` is called, the list is cleared, and no new interfaces can be added (closed state).
|
||||
TMycNotifyList<T: IInterface> = record
|
||||
type
|
||||
TTag = Pointer; // Opaque tag used to identify a registered receiver for unsubscription.
|
||||
|
||||
PItem = ^TItem; // Pointer to an internal list item.
|
||||
TItem = record // Internal structure for storing a receiver and list linkage.
|
||||
Next, Prev: PItem; // Pointers to the next and previous items in the doubly linked list.
|
||||
Receiver: T; // The registered interface instance (the event sink).
|
||||
end;
|
||||
|
||||
strict private
|
||||
FFirst: NativeUInt; // Stores the first receiver if no list is allocated, or acts as a combined lock and state field.
|
||||
// Bit 0: Lock state (0 = locked, 1 = unlocked).
|
||||
// Bit 1: Finalized state (0 = not finalized, 1 = finalized).
|
||||
// Other bits (if not 0 and bit 0 is 1) can be a direct interface pointer if FList is nil.
|
||||
FList: PItem; // Head of the linked list for additional receivers beyond the first one.
|
||||
|
||||
class function AllocItem: PItem; static; inline; // Allocates and initializes memory for a new TItem.
|
||||
class procedure FreeItem( Item: PItem ); static; inline; // Frees memory previously allocated for a TItem.
|
||||
|
||||
public
|
||||
procedure Create; // Initializes the notification list, preparing it for use.
|
||||
procedure Destroy; // Cleans up all resources, including unadvising all receivers. Assumes no concurrent access.
|
||||
function Advise(const Receiver: T): TTag; // Registers a receiver interface and returns an opaque tag for later unsubscription.
|
||||
procedure Unadvise(Tag: TTag); // Unregisters a specific receiver using the tag obtained from Advise.
|
||||
procedure UnadviseAll; // Unregisters all currently advised receivers.
|
||||
procedure Lock; inline; // Acquires an exclusive lock for thread-safe operations on the list.
|
||||
procedure Release; inline;// Releases the previously acquired exclusive lock.
|
||||
function IsLocked: Boolean; inline; // Checks if the list is currently locked by any thread.
|
||||
procedure Notify(Func: TPredicate<T>); // Iterates through registered receivers and invokes the predicate; removes receiver if predicate returns false.
|
||||
end;
|
||||
|
||||
implementation
|
||||
@@ -69,9 +67,6 @@ var
|
||||
begin
|
||||
Assert( IsLocked );
|
||||
|
||||
if IsFinalized then
|
||||
exit( 0 );
|
||||
|
||||
if FFirst=0 then
|
||||
begin
|
||||
IInterface( FFirst ) := Receiver;
|
||||
@@ -108,13 +103,6 @@ begin
|
||||
Result := AllocMem( sizeof( TItem ) );
|
||||
end;
|
||||
|
||||
procedure TMycNotifyList<T>.Finalize;
|
||||
begin
|
||||
Assert( IsLocked );
|
||||
UnadviseAll;
|
||||
FFirst := FFirst or 2;
|
||||
end;
|
||||
|
||||
class procedure TMycNotifyList<T>.FreeItem(Item: PItem);
|
||||
begin
|
||||
FreeMem( Item, sizeof( TItem ) );
|
||||
@@ -125,20 +113,12 @@ begin
|
||||
Result := FFirst and 1 = 0;
|
||||
end;
|
||||
|
||||
function TMycNotifyList<T>.IsFinalized: Boolean;
|
||||
begin
|
||||
Result := FFirst and 2 <> 0;
|
||||
end;
|
||||
|
||||
procedure TMycNotifyList<T>.Notify(Func: TPredicate<T>);
|
||||
var
|
||||
Item, P: PItem;
|
||||
begin
|
||||
Assert( IsLocked );
|
||||
|
||||
if IsFinalized then
|
||||
exit;
|
||||
|
||||
if FFirst<>0 then
|
||||
if not Func( IInterface( FFirst ) ) then
|
||||
IInterface( FFirst ) := nil;
|
||||
@@ -165,15 +145,15 @@ var
|
||||
begin
|
||||
Assert( IsLocked );
|
||||
|
||||
if IsFinalized then
|
||||
exit;
|
||||
|
||||
if NativeUInt(Tag) = FFirst then
|
||||
begin
|
||||
IInterface( FFirst ) := nil;
|
||||
exit;
|
||||
end;
|
||||
|
||||
if FList = nil then
|
||||
exit;
|
||||
|
||||
Item := PItem( Tag );
|
||||
|
||||
if Item = FList then
|
||||
@@ -193,9 +173,6 @@ procedure TMycNotifyList<T>.UnadviseAll;
|
||||
begin
|
||||
Assert( IsLocked );
|
||||
|
||||
if IsFinalized then
|
||||
exit;
|
||||
|
||||
IInterface( FFirst ) := nil;
|
||||
while FList<>nil do
|
||||
Unadvise( TTag( FList ) );
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
unit Myc.Core.Tasks;
|
||||
|
||||
interface
|
||||
|
||||
uses
|
||||
System.SysUtils, System.Classes, System.SyncObjs,
|
||||
Myc.Core.Atomic, Myc.Signals;
|
||||
|
||||
type
|
||||
IMycTaskFactory = interface
|
||||
{$region 'property access'}
|
||||
function GetThreadCount: Integer;
|
||||
{$endregion}
|
||||
function CreateThread(const Proc: TProc): IMycState;
|
||||
function InMainThread: Boolean;
|
||||
function InWorkerThread: Boolean;
|
||||
function Run(StartCount: Integer; Job: TProc): IMycSubscriber;
|
||||
procedure Teardown;
|
||||
procedure WaitFor(State: IMycState);
|
||||
property ThreadCount: Integer read GetThreadCount;
|
||||
end;
|
||||
|
||||
TMycTaskFactory = class(TInterfacedObject, IMycTaskFactory)
|
||||
type
|
||||
ETaskException = class(Exception) end;
|
||||
private
|
||||
[volatile]
|
||||
FException: TObject; // Holds the first exception object from a worker thread
|
||||
[volatile]
|
||||
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
|
||||
FWorkStack: TMycAtomicStack<TProc>; // Stack of pending jobs
|
||||
FWorkThreads: TArray<TThread>; // Array of worker threads
|
||||
procedure WorkerThread;
|
||||
|
||||
protected
|
||||
procedure EnqueueJob(const Job: TProc);
|
||||
procedure ExecuteJob;
|
||||
function GetThreadCount: Integer;
|
||||
property WaitSemaphores: TMycAtomicStack<TSemaphore> read FWaitSemaphores;
|
||||
|
||||
public
|
||||
constructor Create;
|
||||
destructor Destroy; override;
|
||||
class function CreateAnonymousThread(const DbgName: String; const Proc: TProc): TThread;
|
||||
function CreateThread(const Proc: TProc): IMycState;
|
||||
procedure HandleException;
|
||||
function Run(StartCount: Integer; Job: TProc): IMycSubscriber;
|
||||
procedure WaitFor(State: IMycState);
|
||||
procedure Teardown;
|
||||
function InMainThread: Boolean;
|
||||
function InWorkerThread: Boolean;
|
||||
end;
|
||||
|
||||
implementation
|
||||
|
||||
type
|
||||
TMyc2PendingJob = class(TInterfacedObject, IMycSubscriber)
|
||||
private
|
||||
[volatile]
|
||||
FCount: Integer; // Countdown counter
|
||||
FJob: TProc; // The job to execute when count reaches zero
|
||||
FOwner: TMycTaskFactory; // The task factory to enqueue the job on
|
||||
|
||||
protected
|
||||
function Notify: Boolean;
|
||||
|
||||
public
|
||||
constructor Create(StartCountValue: Integer; OwnerTaskFactory: TMycTaskFactory; const JobProc: TProc);
|
||||
property Owner: TMycTaskFactory read FOwner;
|
||||
end;
|
||||
|
||||
TMyc2TaskWait = class sealed(TInterfacedObject, IMycSubscriber)
|
||||
private
|
||||
[volatile]
|
||||
FSemaphore: TSemaphore; // Semaphore to be released on notification
|
||||
|
||||
protected
|
||||
function Notify: Boolean;
|
||||
|
||||
public
|
||||
constructor Create(SemaphoreToSignal: TSemaphore);
|
||||
end;
|
||||
|
||||
{ TMycTaskFactory }
|
||||
|
||||
constructor TMycTaskFactory.Create;
|
||||
var
|
||||
i: Integer;
|
||||
begin
|
||||
inherited Create;
|
||||
|
||||
Assert(InMainThread); // Ensure factory is created in the main thread
|
||||
|
||||
FWorkGate := TSemaphore.Create(nil, 0, MaxInt, ''); // Initial count is 0, workers will wait
|
||||
|
||||
SetLength(FWorkThreads, TThread.ProcessorCount); // Create one thread per processor core
|
||||
for i := 0 to High(FWorkThreads) do
|
||||
begin
|
||||
FWorkThreads[i] := CreateAnonymousThread('Thread pool [' + IntToStr(i) + ']', WorkerThread);
|
||||
TInterlocked.Increment(FThreadsRunning); // Increment active thread counter
|
||||
FWorkThreads[i].Start;
|
||||
end;
|
||||
end;
|
||||
|
||||
destructor TMycTaskFactory.Destroy;
|
||||
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}
|
||||
begin
|
||||
Result := TThread.CreateAnonymousThread(Proc);
|
||||
|
||||
{$IFDEF MSWINDOWS}
|
||||
// Set priority lower than MainThread priority if created from main thread
|
||||
if TThread.CurrentThread.ThreadID = MainThreadID then
|
||||
begin
|
||||
prio := TThread.CurrentThread.Priority;
|
||||
if prio > Low(TThreadPriority) then
|
||||
prio := TThreadPriority(Ord(prio) - 1); // Decrease priority by one step
|
||||
|
||||
Result.Priority := prio;
|
||||
end;
|
||||
{$ENDIF MSWINDOWS}
|
||||
|
||||
if DbgName <> '' then
|
||||
Result.NameThreadForDebugging(DbgName); // Set thread name for debugging
|
||||
end;
|
||||
|
||||
function TMycTaskFactory.CreateThread(const Proc: TProc): IMycState;
|
||||
var
|
||||
res: IMycSemaphore;
|
||||
capturedProc: TProc;
|
||||
begin
|
||||
res := Signals.CreateSemaphore(1); // Create a semaphore that will be signaled when the proc finishes
|
||||
|
||||
capturedProc := Proc; // Capture Proc for the anonymous method
|
||||
CreateAnonymousThread('Thread',
|
||||
procedure
|
||||
begin
|
||||
try
|
||||
capturedProc(); // Execute the provided procedure
|
||||
finally
|
||||
capturedProc := nil; // Clear the captured proc
|
||||
res.Notify; // Signal completion
|
||||
end;
|
||||
end).Start;
|
||||
|
||||
exit(res.State); // Return the state interface of the semaphore
|
||||
end;
|
||||
|
||||
procedure TMycTaskFactory.EnqueueJob(const Job: TProc);
|
||||
begin
|
||||
if Assigned(Job) then
|
||||
begin
|
||||
FWorkStack.Push(Job); // Push job onto the lock-free stack
|
||||
FWorkGate.Release; // Signal a worker thread that a job is available
|
||||
end;
|
||||
end;
|
||||
|
||||
procedure TMycTaskFactory.WorkerThread;
|
||||
begin
|
||||
try
|
||||
repeat
|
||||
FWorkGate.Acquire; // Wait for a job to be available or for termination
|
||||
if FTerminated = 0 then // Check if termination has been requested
|
||||
ExecuteJob; // Execute a job from the stack
|
||||
until FTerminated <> 0; // Loop until termination is signaled
|
||||
finally
|
||||
TInterlocked.Decrement(FThreadsRunning); // Decrement active thread counter
|
||||
end;
|
||||
end;
|
||||
|
||||
function TMycTaskFactory.GetThreadCount: Integer;
|
||||
begin
|
||||
Result := Length(FWorkThreads);
|
||||
end;
|
||||
|
||||
procedure TMycTaskFactory.HandleException;
|
||||
var
|
||||
ex: TObject;
|
||||
begin
|
||||
if InMainThread then
|
||||
begin
|
||||
ex := AtomicExchange(Pointer(FException), nil); // Atomically retrieve and clear the stored exception
|
||||
if ex <> nil then
|
||||
raise ex; // Re-raise the exception in the main thread
|
||||
end;
|
||||
end;
|
||||
|
||||
function TMycTaskFactory.InMainThread: Boolean;
|
||||
begin
|
||||
Result := TThread.Current.ThreadID = MainThreadID;
|
||||
end;
|
||||
|
||||
function TMycTaskFactory.InWorkerThread: Boolean;
|
||||
var
|
||||
currentThreadId: TThreadID;
|
||||
i: Integer;
|
||||
begin
|
||||
currentThreadId := TThread.Current.ThreadID;
|
||||
if currentThreadId = MainThreadID then
|
||||
exit(false); // Not a worker thread if it's the main thread
|
||||
|
||||
for i := 0 to High(FWorkThreads) do
|
||||
if FWorkThreads[i].ThreadID = currentThreadId then
|
||||
exit(true); // Current thread is one of the worker threads
|
||||
exit(false); // Not found in worker thread list
|
||||
end;
|
||||
|
||||
function TMycTaskFactory.Run(StartCount: Integer; Job: TProc): IMycSubscriber;
|
||||
begin
|
||||
if FTerminated <> 0 then
|
||||
raise ETaskException.Create('Task factory terminated');
|
||||
|
||||
if not Assigned(Job) then
|
||||
exit(Signals.Null); // Return a null subscriber if no job is provided
|
||||
|
||||
if StartCount <= 0 then
|
||||
begin
|
||||
EnqueueJob(Job); // Enqueue immediately if no countdown needed
|
||||
Result := Signals.Null;
|
||||
end
|
||||
else
|
||||
// Create a pending job that waits for StartCount notifications
|
||||
Result := TMyc2PendingJob.Create(StartCount, Self, Job);
|
||||
end;
|
||||
|
||||
procedure TMycTaskFactory.Teardown;
|
||||
var
|
||||
i: Integer;
|
||||
s: TSemaphore;
|
||||
job: TProc; // Variable to receive popped job to ensure it's processed/discarded
|
||||
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
|
||||
|
||||
// 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
|
||||
s.Free;
|
||||
s := FWaitSemaphores.Pop;
|
||||
end;
|
||||
end;
|
||||
|
||||
procedure TMycTaskFactory.WaitFor(State: IMycState);
|
||||
var
|
||||
lock: 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
|
||||
|
||||
lock := FWaitSemaphores.Pop(); // Try to get a semaphore from the pool
|
||||
if lock = nil then
|
||||
lock := TSemaphore.Create(nil, 0, 1, ''); // Create new one if pool is empty (initial count 0)
|
||||
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
|
||||
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
|
||||
end;
|
||||
|
||||
procedure TMycTaskFactory.ExecuteJob;
|
||||
var
|
||||
job: TProc;
|
||||
begin
|
||||
job := FWorkStack.Pop(); // Pop a job from the stack
|
||||
|
||||
if Assigned(job) then
|
||||
begin
|
||||
try
|
||||
job(); // Execute the 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.
|
||||
end;
|
||||
end;
|
||||
end;
|
||||
|
||||
{ TMyc2PendingJob }
|
||||
|
||||
constructor TMyc2PendingJob.Create(StartCountValue: Integer; OwnerTaskFactory: TMycTaskFactory; const JobProc: TProc);
|
||||
begin
|
||||
inherited Create;
|
||||
Assert(StartCountValue > 0); // StartCount must be positive
|
||||
FCount := StartCountValue;
|
||||
FOwner := OwnerTaskFactory;
|
||||
FJob := JobProc;
|
||||
end;
|
||||
|
||||
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.
|
||||
if newCount < -MaxInt div 2 then
|
||||
TInterlocked.Increment(FCount);
|
||||
|
||||
if newCount = 0 then // If counter reaches exactly zero
|
||||
begin
|
||||
// FOwner and FJob are captured by the class instance
|
||||
if Assigned(FOwner) and Assigned(FJob) then // Ensure owner and job are still valid
|
||||
begin
|
||||
FOwner.EnqueueJob(FJob); // Enqueue the job
|
||||
FJob := nil; // Clear the job reference to prevent re-enqueuing and allow ARC
|
||||
end;
|
||||
end;
|
||||
Result := newCount > 0; // Returns true if further notifications are expected (count is still positive)
|
||||
end;
|
||||
|
||||
{ TMyc2TaskWait }
|
||||
|
||||
constructor TMyc2TaskWait.Create(SemaphoreToSignal: TSemaphore);
|
||||
begin
|
||||
inherited Create;
|
||||
FSemaphore := SemaphoreToSignal;
|
||||
end;
|
||||
|
||||
function TMyc2TaskWait.Notify: Boolean;
|
||||
var
|
||||
s: 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
|
||||
end;
|
||||
|
||||
initialization
|
||||
IsMultiThread := true; // Mark the application as multi-threaded
|
||||
end.
|
||||
+84
-73
@@ -20,11 +20,12 @@ type
|
||||
FSignal: TMycSignal;
|
||||
FTag: TMycNotifyList<IMycSubscriber>.TTag;
|
||||
public
|
||||
procedure Setup(ASignal: TMycSignal; ATag: TMycNotifyList<IMycSubscriber>.TTag); inline;
|
||||
class operator Assign(var Dest: TMycSubscription; const [ref] Src:
|
||||
TMycSubscription);
|
||||
class operator Initialize(out Dest: TMycSubscription);
|
||||
class operator Finalize(var Dest: TMycSubscription);
|
||||
class operator Assign(var Dest: TMycSubscription; const [ref] Src: TMycSubscription);
|
||||
|
||||
procedure Setup(ASignal: TMycSignal; ATag: TMycNotifyList<IMycSubscriber>.TTag); inline;
|
||||
procedure Unsubscribe;
|
||||
end;
|
||||
|
||||
IMycSignal = interface
|
||||
@@ -32,18 +33,9 @@ type
|
||||
end;
|
||||
|
||||
TMycSignal = class abstract( TInterfacedObject, IMycSignal )
|
||||
strict private
|
||||
FSubscribers: TMycNotifyList<IMycSubscriber>;
|
||||
private
|
||||
procedure Unsubscribe(Tag: TMycNotifyList<IMycSubscriber>.TTag);
|
||||
protected
|
||||
procedure Lock;
|
||||
procedure Unlock;
|
||||
procedure Finalize;
|
||||
procedure Notify;
|
||||
public
|
||||
function Subscribe(const Subscriber: IMycSubscriber): TMycSubscription;
|
||||
property Subscribers: TMycNotifyList<IMycSubscriber> read FSubscribers;
|
||||
function Subscribe(const Subscriber: IMycSubscriber): TMycSubscription; virtual; abstract;
|
||||
procedure Unsubscribe(Tag: TMycNotifyList<IMycSubscriber>.TTag); virtual; abstract;
|
||||
end;
|
||||
|
||||
IMycState = interface( IMycSignal )
|
||||
@@ -61,18 +53,28 @@ type
|
||||
end;
|
||||
|
||||
TMycSemaphore = class(TMycSignal, IMycSemaphore, IMycState)
|
||||
strict private
|
||||
FSubscribers: TMycNotifyList<IMycSubscriber>;
|
||||
private
|
||||
[volatile] FCount: Integer;
|
||||
function GetState: IMycState;
|
||||
function GetIsSet: Boolean;
|
||||
protected
|
||||
function Notify: Boolean;
|
||||
public
|
||||
constructor Create(ACount: Integer);
|
||||
destructor Destroy; override;
|
||||
function Subscribe(const Subscriber: IMycSubscriber): TMycSubscription; override;
|
||||
procedure Unsubscribe(Tag: TMycNotifyList<IMycSubscriber>.TTag); override;
|
||||
function Notify: Boolean;
|
||||
end;
|
||||
|
||||
Signals = record
|
||||
strict private
|
||||
class var
|
||||
FNull: IMycSemaphore;
|
||||
class constructor Create;
|
||||
public
|
||||
class function CreateSemaphore(Count: Integer): IMycSemaphore; static;
|
||||
class property Null: IMycSemaphore read FNull;
|
||||
end;
|
||||
|
||||
implementation
|
||||
@@ -80,63 +82,23 @@ implementation
|
||||
uses
|
||||
System.SyncObjs;
|
||||
|
||||
procedure TMycSignal.Finalize;
|
||||
begin
|
||||
FSubscribers.Finalize;
|
||||
end;
|
||||
|
||||
procedure TMycSignal.Lock;
|
||||
begin
|
||||
FSubscribers.Lock;
|
||||
end;
|
||||
|
||||
procedure TMycSignal.Notify;
|
||||
begin
|
||||
FSubscribers.Notify(
|
||||
function( Subscriber: IMycSubscriber ): Boolean
|
||||
begin
|
||||
Result := Subscriber.Notify;
|
||||
end );
|
||||
end;
|
||||
|
||||
function TMycSignal.Subscribe(const Subscriber: IMycSubscriber): TMycSubscription;
|
||||
begin
|
||||
if not Assigned(Subscriber) then
|
||||
exit;
|
||||
|
||||
FSubscribers.Lock;
|
||||
try
|
||||
Result.Setup( Self, FSubscribers.Advise( Subscriber ) );
|
||||
finally
|
||||
FSubscribers.Release;
|
||||
end;
|
||||
end;
|
||||
|
||||
procedure TMycSignal.Unlock;
|
||||
begin
|
||||
|
||||
end;
|
||||
|
||||
procedure TMycSignal.Unsubscribe(Tag: TMycNotifyList<IMycSubscriber>.TTag);
|
||||
begin
|
||||
if Tag=nil then
|
||||
exit;
|
||||
|
||||
FSubscribers.Lock;
|
||||
try
|
||||
FSubscribers.Unadvise( Tag );
|
||||
finally
|
||||
FSubscribers.Release;
|
||||
end;
|
||||
end;
|
||||
|
||||
procedure TMycSubscription.Setup(ASignal: TMycSignal; ATag:
|
||||
TMycNotifyList<IMycSubscriber>.TTag);
|
||||
begin
|
||||
Unsubscribe;
|
||||
FSignal := ASignal;
|
||||
FTag := ATag;
|
||||
end;
|
||||
|
||||
procedure TMycSubscription.Unsubscribe;
|
||||
begin
|
||||
if FTag<>nil then
|
||||
begin
|
||||
FSignal.Unsubscribe( FTag );
|
||||
FTag := nil;
|
||||
end;
|
||||
end;
|
||||
|
||||
class operator TMycSubscription.Assign(var Dest: TMycSubscription; const [ref]
|
||||
Src: TMycSubscription);
|
||||
begin
|
||||
@@ -150,33 +112,42 @@ end;
|
||||
|
||||
class operator TMycSubscription.Finalize(var Dest: TMycSubscription);
|
||||
begin
|
||||
if Dest.FTag=nil then
|
||||
exit;
|
||||
Dest.FSignal.Unsubscribe( Dest.FTag );
|
||||
Dest.Unsubscribe;
|
||||
end;
|
||||
|
||||
constructor TMycSemaphore.Create(ACount: Integer);
|
||||
begin
|
||||
inherited Create;
|
||||
FCount := ACount;
|
||||
FSubscribers.Create;
|
||||
end;
|
||||
|
||||
destructor TMycSemaphore.Destroy;
|
||||
begin
|
||||
FSubscribers.Destroy;
|
||||
inherited;
|
||||
end;
|
||||
|
||||
function TMycSemaphore.Notify: Boolean;
|
||||
begin
|
||||
Lock;
|
||||
FSubscribers.Lock;
|
||||
try
|
||||
var n := TInterlocked.Decrement( FCount );
|
||||
if n < -MaxInt div 2 then
|
||||
TInterlocked.Increment( FCount );
|
||||
|
||||
if n = 0 then
|
||||
Notify;
|
||||
FSubscribers.Notify(
|
||||
function( Subscriber: IMycSubscriber ): Boolean
|
||||
begin
|
||||
Result := Subscriber.Notify;
|
||||
end );
|
||||
|
||||
Result := n > 0;
|
||||
if not Result then
|
||||
Finalize;
|
||||
FSubscribers.UnadviseAll;
|
||||
finally
|
||||
Release;
|
||||
FSubscribers.Release;
|
||||
end;
|
||||
end;
|
||||
|
||||
@@ -190,6 +161,46 @@ begin
|
||||
exit( Self );
|
||||
end;
|
||||
|
||||
function TMycSemaphore.Subscribe(const Subscriber: IMycSubscriber):
|
||||
TMycSubscription;
|
||||
begin
|
||||
if not Assigned(Subscriber) then
|
||||
exit;
|
||||
|
||||
Subscriber._AddRef;
|
||||
try
|
||||
FSubscribers.Lock;
|
||||
try
|
||||
if FCount <= 0 then
|
||||
Subscriber.Notify
|
||||
else
|
||||
Result.Setup( Self, FSubscribers.Advise( Subscriber ) );
|
||||
finally
|
||||
FSubscribers.Release;
|
||||
end;
|
||||
finally
|
||||
Subscriber._Release;
|
||||
end;
|
||||
end;
|
||||
|
||||
procedure TMycSemaphore.Unsubscribe(Tag: TMycNotifyList<IMycSubscriber>.TTag);
|
||||
begin
|
||||
if Tag=nil then
|
||||
exit;
|
||||
|
||||
FSubscribers.Lock;
|
||||
try
|
||||
FSubscribers.Unadvise( Tag );
|
||||
finally
|
||||
FSubscribers.Release;
|
||||
end;
|
||||
end;
|
||||
|
||||
class constructor Signals.Create;
|
||||
begin
|
||||
FNull := TMycSemaphore.Create( 0 );
|
||||
end;
|
||||
|
||||
{ Signals }
|
||||
|
||||
class function Signals.CreateSemaphore(Count: Integer): IMycSemaphore;
|
||||
|
||||
Reference in New Issue
Block a user