Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TCriticalSection TryEnter Method Always Returns True

Tags:

winapi

delphi

When calling the TryEnter method on a TCriticalSection the result is always true. Surely this should only return true if it is able to aquire the lock?

var
  MyCritSect: TCriticalSection;

begin
  MyCritSect := TCriticalSection.Create;
  try
    //    MyCritSect.Enter;
    Writeln(BoolToStr(MyCritSect.TryEnter, True)); // This should return True
    Writeln(BoolToStr(MyCritSect.TryEnter, True)); // This should return False?
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Even if you uncomment the MyCritSect.Enter; line it still returns True for both calls to TryEnter.

I am using Delphi XE and Windows 10.

like image 239
Donovan Boddy Avatar asked Sep 26 '22 23:09

Donovan Boddy


1 Answers

Critical sections are re-entrant locks. From the documentation:

When a thread owns a critical section, it can make additional calls to EnterCriticalSection or TryEnterCriticalSection without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section that it already owns.

Your call to TryEnter will fail if made from a different thread, and the first thread already owns the lock.

like image 98
David Heffernan Avatar answered Sep 29 '22 05:09

David Heffernan