gpt4 book ai didi

multithreading - Delphi Singleton 双重检查锁定

转载 作者:行者123 更新时间:2023-12-03 15:51:24 26 4
gpt4 key购买 nike

我想实现一个单例关键部分,以保护多个类中的某些代码(不要再问了.​​.....)。我见过Delphi Singleton PatternAquire Singleton class Instance Multithread但这些使用全局函数来返回单例,我不希望这样。所以,我实现了我自己的版本:

unit SynchronizationHandler;

interface

uses
SyncObjs;

type
TSynchronizationHandler = class
strict private
FCriticalSection: TCriticalSection;
private
class var FSingletonCriticalSection: TCriticalSection;
class var FInstance: TSynchronizationHandler;
public
constructor Create;
destructor Destroy; override;

procedure Lock;
procedure Release;
class function Instance: TSynchronizationHandler;
end;

implementation

{ TSynchronizationHandler }

constructor TSynchronizationHandler.Create;
begin
FCriticalSection := TCriticalSection.Create;
end;

destructor TSynchronizationHandler.Destroy;
begin
FCriticalSection.Destroy;
end;

{Doublec check locking for this singletone}
class function TSynchronizationHandler.Instance: TSynchronizationHandler;
begin
if not Assigned(FInstance) then
begin
FSingletonCriticalSection.Acquire;
try
if not Assigned(FInstance) then
FInstance := TSynchronizationHandler.Create;
finally
FSingletonCriticalSection.Release;
end;
end;

Result := FInstance;
end;

procedure TSynchronizationHandler.Lock;
begin
FCriticalSection.Acquire;
end;

procedure TSynchronizationHandler.Release;
begin
FCriticalSection.Release;
end;

initialization
TSynchronizationHandler.FSingletonCriticalSection := TCriticalSection.Create;

finalization
if Assigned(TSynchronizationHandler.FInstance) then
TSynchronizationHandler.Instance.Free;

TSynchronizationHandler.FSingletonCriticalSection.Free;

end.

它可以工作,但我不喜欢初始化\终结部分。有没有其他方法可以在不使用全局变量、函数的情况下完成此任务?

最佳答案

如果您想将所有必要的代码封装在类的命名空间内,那么您可以将 initializationfinalization 部分替换为 class constructor和一个class destructor , 分别。这些将从单元初始化和最终化过程中隐式调用。

关于multithreading - Delphi Singleton 双重检查锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54090241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com