我有一个对象x,需要从几个(5+个线程)访问.对象的结构是
Tx = class
private
Fx: integer;
public
property x: integer read Fx read Fx;
etc;
Run Code Online (Sandbox Code Playgroud)
什么是更好(最优雅)的保护方式:
一个)
Tx = class
private
Fx: integer;
public
property x: integer read Fx read Fx;
public
constructor Create; <--- Create the criticalsection here
destructor Destroy; <--destroy it here
etc;
var
cs: TCriticalSection;
Obj: Tx;
function GetSafeObject(): Tx;
begin
CS.Enter;
try
Result:= Obj;
finally
CS.Leave;
Run Code Online (Sandbox Code Playgroud)
结束;
并始终将对象作为GetSafeObj()访问.x:= 3;
要么
Tx = class
private
Fx: integer;
FCS: TCriticalSection;
public
property x: integer read GerX read …Run Code Online (Sandbox Code Playgroud)