gpt4 book ai didi

pthreads - 如何处理 pthread_mutex_unlock 失败?

转载 作者:行者123 更新时间:2023-12-02 20:35:53 26 4
gpt4 key购买 nike

假设一个线程成功调用pthread_mutex_lock,在同一线程中调用pthread_mutex_unlock是否仍然可能失败?如果是这样,除了中止线程之外,您实际上还能做些什么吗?

if(pthread_mutex_lock(&m) == 0)
{
// got the lock, let's do some work

if(pthread_mutex_unlock(&m) != 0) // can this really fail?
{
// ok, we have a lock but can't unlock it?
}
}

来自this pagepthread_mutex_unlock() 可能出现的错误是:

[EINVAL] The value specified by mutex does not refer to an initialised mutex object.

如果锁定成功,则不太可能失败。

[EAGAIN] The mutex could not be acquired because the maximum number of recursive locks for mutex has been exceeded.

真的吗?用于解锁?

The pthread_mutex_unlock() function may fail if:

[EPERM] The current thread does not own the mutex.

同样,如果锁定成功,那么这种情况也不应该发生。

所以,我的想法是,如果有一个成功的锁定,那么在这种情况下解锁应该永远不会失败,从而使错误检查和后续处理代码变得毫无意义。

最佳答案

在你喊出“胜利”之前。我最终在这个页面上寻找我的一个程序在 pthread_mutex_unlock 上失败的原因(在 HP-UX 上,而不是 Linux)。

if (pthread_mutex_unlock(&mutex) != 0)
throw YpException("unlock %s failed: %s", what.c_str(), strerror(errno));

在数百万次愉快的处决之后,这对我来说失败了。errno 是 EINTR,尽管我现在发现我不应该检查 errno,而应该检查返回值。但尽管如此,返回值不是 0。我可以从数学上证明,在那个位置我确实拥有一把有效的锁。

所以我们只能说你的理论正面临压力,尽管需要更多的研究;-)

关于pthreads - 如何处理 pthread_mutex_unlock 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7422316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com