首页 > 解决方案 > TMutex 在 Delphi 中是可重入的吗?

问题描述

我正在创建我的互斥锁:

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

并在使用相同创建的互斥锁调用另一个方法的方法中使用它:

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;

嵌套互斥体是否安全?

标签: delphimutexdelphi-10.1-berlin

解决方案


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.


推荐阅读