可能是我误解了一些东西,但......
当我调用pthread_mutex_lock()然后再次调用相同的线程中的pthread_mutex_lock()而不调用pthread_mutex_unlock()时,pthread_mutex_lock()的第二次调用将阻塞。
但是:当我调用EnterCriticalSection()并再次从相同的线程调用EnterCriticalSection()而不调用LeaveCriticalSection()时,EnterCriticalSection()的第二次调用将不会阻塞,因为它被调出相同的线程(对我来说这是一个非常奇怪的行为)。
所以我的问题是有一个可用的WinAPI函数,其行为类似于pthread_mutex_lock()并且独立于线程上下文锁定?
我知道用于Windows的libpthread,但我更喜欢在这里使用WinAPI函数。
答案 0 :(得分:2)
您可以使用最大计数设置为1的信号量。 见Semaphore Objects
当您成功获取信号量时,其计数会递减:在我们的情况下为零。 没有其他线程可以获取它,包括当前线程。
答案 1 :(得分:0)
pthread_mutex_lock文档:
If the mutex type is PTHREAD_MUTEX_RECURSIVE, then the mutex maintains the concept of a lock count. When a thread successfully acquires a mutex for the first time, the lock count is set to one. Every time a thread relocks this mutex, the lock count is incremented by one. Each time the thread unlocks the mutex, the lock count is decremented by one. When the lock count reaches zero, the mutex becomes available for other threads to acquire. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, an error will be returned.
MSDN ReleaseMutex声明:
A thread can specify a mutex that it already owns in a call to one of the wait functions without blocking its execution. This prevents a thread from deadlocking itself while waiting for a mutex that it already owns. However, to release its ownership, the thread must call ReleaseMutex one time for each time that it obtained ownership (either through CreateMutex or a wait function).
wait functions相当于pthread_mutex_lock。
请参阅Mutex Objects (Windows)以获取有关此API的更多详细信息。
和this stackoverflow条目以查看CRITICAL_SECTION对象包含的内容。这将披露
CRITICAL_SECTION对象包含值LockCount
以允许递归使用。请参阅EnterCriticalSection function以了解此功能。