I have an object x that needs to be accessed from several (5+ threads). The structure of the object is
Tx = class
private
Fx: integer;
public
property x: integer read Fx read Fx;
etc;
What is the better (most elegant) way of protection:
a)
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;
end;
and access always the object as GetSafeObj().x:= 3;
or
Tx = class
private
Fx: integer;
FCS: TCriticalSection;
public
property x: integer read GerX read SetX;
public
constructor Create; <--- Create the criticalsection here
destructor Destroy; <--destroy it here
etc;
where
function Tx.Getx(): integer;
begin
CS.Enter;
try
Result:= Fx;
finally
CS.Leave;
end;
end;
end;
and always access the object normally. I guess the first option is more elegant, even if both methods should work fine. Ay comments?