Search code examples
delphimutexdelphi-10.1-berlin

Is TMutex re-entrant in Delphi?


I'm creating my mutex:

 FMutex := TMutex.Create(nil, False, 'SomeDumbText');

and use it in a method which calls another method using the same created mutex:

procedure a;
begin
  FMutex.Acquire;
  try
    //do some work here and maybe call b
  finally
    FMutex.Release;
  end;
end;

procedure b;
begin
  FMutex.Acquire;
  try
    //do some work here
  finally
    FMutex.Release;
  end;
end;

It is safe to have nested mutex?


Solution

  • TMutex is implemented over the underlying platform object. On Windows that is the mutex object. On the other platforms that is the pthread mutex.

    Your question is whether or not TMutex is re-entrant. In turn, the answer depends on whether or not the underlying platform object is re-entrant. The Windows mutex is always re-entrant, the pthread mutex is optionally re-entrant, and the Delphi TMutex code chooses to use it in re-entrant mode, by calling pthread_mutexattr_settype(Attr, PTHREAD_MUTEX_RECURSIVE).

    So, the answer to your question is that TMutex is re-entrant.