Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can TCriticalSection.Acquire be safely called more than one time by a thread?

On Windows platform, TCriticalSection is implemented by calling the Windows API EnterCriticalSection/LeaveCriticalSection. Microsoft documentation explicitly says that after a thread has ownership of a critical section, it can make additional calls to EnterCriticalSection.

So far so good.

But what about the behavior under the other platforms Delphi supports such as OSX, iOS and Android?

Other platforms seems to make use of TMonitor. So the question could be rewritten against TMonitor.

like image 441
fpiette Avatar asked Feb 11 '14 12:02

fpiette


1 Answers

The implementation of TCriticalSection under other platforms than Windows simply uses TMonitor. So the answer to your question reduces to the behaviour of TMonitor.Enter. At least the documentation states that TMonitor.Enter is reentrant.

This part of the documentation would mean a "yes" to your answer:

Prohibits the access of all other threads but the calling one to the specified object.

The relevant code part of TMonitor is in TMonitor.TryEnter:

function TMonitor.TryEnter: Boolean;
begin
  if FOwningThread = GetCurrentThreadId then  // check for recursion
  begin
    ...
    Result := True;
  ...
like image 107
Uwe Raabe Avatar answered Nov 12 '22 14:11

Uwe Raabe