1

可能是我误解了什么,但是......

当我调用 pthread_mutex_lock() 然后再次从同一个线程中调用 pthread_mutex_lock() 而不调用 pthread_mutex_unlock() 时,第二次调用 pthread_mutex_lock() 将阻塞。

但是:当我调用 EnterCriticalSection() 并再次从同一个线程中调用 EnterCriticalSection() 而不调用 LeaveCriticalSection() 时,第二次调用 EnterCriticalSection() 将不会阻塞,因为它是从同一个线程中调用的(这很奇怪我的行为)。

所以我的问题是有一个可用的 WinAPI 函数,其行为类似于 pthread_mutex_lock() 并且锁定独立于线程上下文?

我知道适用于 Windows 的 libpthread,但我更喜欢在这里使用 WinAPI 函数。

4

2 回答 2

2

You could use a Semaphore with the maximum count set to one. See Semaphore Objects

When you successfully acquire the semaphore, its count is decremented: going to zero in our case. No other thread can acquire it, including the current one.

于 2013-07-03T08:58:49.493 回答
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).

等待函数等价于pthread_mutex_lock。

请参阅互斥对象 (Windows)以获取有关此 API 的更多详细信息。

这个stackoverflow 条目可以查看 CRITICAL_SECTION 对象包含的内容。这将揭示 CRITICAL_SECTION 对象持有 - 除其他外 - 一个LockCount允许递归使用的值。请参阅EnterCriticalSection 函数以了解此功能。

于 2013-07-03T08:02:04.313 回答