线程能否在调用 .ReleaseMutex() 之前多次调用 Mutex 的 .WaitOne() ,反之亦然?
Can a thread call .WaitOne() of a Mutex more than once before calling .ReleaseMutex() and vice versa?
在我的代码中,如果我的线程在调用 .ReleaseMutex() 之前多次调用 .WaitOne() 会很方便。
反之亦然:在重新启动以调用 .WaitOne() 开始的循环之前调用 .ReleaseMutex() 几次。
一些操作系统/编译器组合允许这样做。有些没有。
互斥量只有两种状态:锁定或解锁。它不能被锁定两次或解锁两次。你想要的东西是信号量:See Here。信号量有计数器,每次 WaitOne
后计数器减 1,每次调用 Release
后计数器加 1。
.NET System.Threading.Mutex
class 使用 Win32 内核互斥对象 re-entrant。以下来自 the documentation 的注释解释了正确的用法:
The thread that owns a mutex can request the same mutex in repeated calls to WaitOne
without blocking its execution. However, the thread must call the ReleaseMutex
method the same number of times to release ownership of the mutex.
很明显,OS 正在计算互斥体进入的次数——它不是 "locked or unlocked" 的二进制状态(除了计数之外,还有一个附加状态 "abandoned").
在我的代码中,如果我的线程在调用 .ReleaseMutex() 之前多次调用 .WaitOne() 会很方便。
反之亦然:在重新启动以调用 .WaitOne() 开始的循环之前调用 .ReleaseMutex() 几次。
一些操作系统/编译器组合允许这样做。有些没有。
互斥量只有两种状态:锁定或解锁。它不能被锁定两次或解锁两次。你想要的东西是信号量:See Here。信号量有计数器,每次 WaitOne
后计数器减 1,每次调用 Release
后计数器加 1。
.NET System.Threading.Mutex
class 使用 Win32 内核互斥对象 re-entrant。以下来自 the documentation 的注释解释了正确的用法:
The thread that owns a mutex can request the same mutex in repeated calls to
WaitOne
without blocking its execution. However, the thread must call theReleaseMutex
method the same number of times to release ownership of the mutex.
很明显,OS 正在计算互斥体进入的次数——它不是 "locked or unlocked" 的二进制状态(除了计数之外,还有一个附加状态 "abandoned").