Delphi - Is there any equivalent to C# lock?

Ondra C. picture Ondra C. · Jun 11, 2010 · Viewed 7.2k times · Source

I'm writing a multi-threaded application in Delphi and need to use something to protect shared resources.

In C# I'd use the "lock" keyword:

private someMethod() {
    lock(mySharedObj) {
        //...do something with mySharedObj
    }
}

In Delphi I couldn't find anything similar, I found just TThread.Synchronize(someMethod) method, which prevents potential conflicts by calling someMethod in main VCL thread, but it isn't exactly what I want to do....

Edit: I'm using Delphi 6

Answer

Lasse V. Karlsen picture Lasse V. Karlsen · Jun 11, 2010

(Un)fortunately you cannot lock on arbitrary objects in Delphi 6 (although you can in more recent versions, 2009 and later), so you need to have a separate lock object, typically a critical section.

TCriticalSection (note: the documentation is from FreePascal, but it exists in Delphi as well):

Example code:

type
  TSomeClass = class
  private
    FLock : TCriticalSection;
  public
    constructor Create();
    destructor Destroy; override;

    procedure SomeMethod;
  end;

constructor TSomeClass.Create;
begin
  FLock := TCriticalSection.Create;
end;

destructor TSomeClass.Destroy;
begin
  FreeAndNil(FLock);
end;

procedure TSomeClass.SomeMethod;
begin
  FLock.Acquire;
  try
    //...do something with mySharedObj
  finally
    FLock.Release;
  end;
end;