Question

Can I have a TCriticalSection object declared as a public field, such as:

type
  TMyObject = class
  public
    CS: TCriticalSection;
  end;

I would like to make that field public to allow any thread enter and leave the critical section object, which internally protects integrity of the TMyObject instance. So, can I declare TCriticalSection object as a public class field ?

Was it helpful?

Solution

The simple answer is yes. A field of a class is a perfectly normal place to hold a TCriticalSection.

In order for a critical section to be able to serialize access to a shared resource, all threads must refer to the same instance of the critical section. So, from that fact you conclude that you need to make sure that all threads refer to the same instance of the class. Then when they read the critical section field of that class, all threads are accessing the same instance of the critical section.

It is usually considered to be bad practice to declare public fields. You would normally expose such a thing through either a property, or methods of the class.

OTHER TIPS

This is what I have done in the past to achieve this:

  TMyObject = class(TObject)
  private
    FCS                 :TCriticalSection;
    FMyProp             :string;
    function GetMyProp :string;
    procedure SetMyProp( const NewValue :string );
  protected
  public
    constructor Create;
    destructor Destroy; override;
    // properties
    property MyProp :string read GetMyProp write SetMyProp;
  end;

followed by the implementation:

constructor TMyObject.Create;
begin
  inherited Create;
  FCS     := TCriticalSection.Create;
  FMyProp := '';
end;

destructor TMyObject.Destroy;
begin
  FCS.Free;
  inherited Destroy;
end;

function TMyObject.GetMyProp :string;
begin
  FCS.Enter;
  try
    result := FMyProp;
  finally
    FCS.Leave;
  end;
end;

procedure TMyObject.SetMyProp( const NewValue :string );
begin
  FCS.Enter;
  try
    FMyProp := NewValue;
  finally
    FCS.Leave;
  end;
end;

Note that I haven't exposed the FCS field.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top