【问题标题】:pthread_mutex_lock() and EnterCriticalSectionpthread_mutex_lock() 和 EnterCriticalSection
【发布时间】:2013-07-03 07:36:48
【问题描述】:

可能是我理解错了,但是……

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

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

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

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

【问题讨论】:

    标签: winapi pthreads mutex


    【解决方案1】:

    您可以使用最大计数设置为 1 的信号量。 见Semaphore Objects

    当您成功获取信号量时,它的计数会递减:在我们的例子中变为零。 没有其他线程可以获取它,包括当前线程。

    【讨论】:

    • 不过还是谢谢!您的回答证实我的解决方案有效:-)
    【解决方案2】:

    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 了解此功能。

    【讨论】:

    • 好的,但这不是我的问题的答案,如何使用 WINAPI 完成这样的线程独立锁......
    • 仅供参考:我添加了 Windows API 提示和链接
    • Windows Mutex 做同样的废话:它不会锁定同一个线程的多个锁。锁计数为 1 的 CreateSemaphore() 和 ReleaseSemaphore() 似乎独立于调用线程上下文完成工作......
    • 我可以问一个问题吗?在一个线程内多次锁定 same 锁的目的是什么?
    • 与 libpthreads 完全兼容——这在跨平台环境中很重要。并且在所有使用的平台上都有相同的错误,而不是不同的行为。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多