如何处理 pthread_mutex_unlock() 错误?

lci*_*cit 4 c++ error-handling pthreads

我正在开发一个也处理错误的线程安全类。我想知道如何处理来自函数 pthread_mutex_unlock() 的可能错误。如果我抛出互斥锁仍然锁定?我应该尝试再次解锁它还是销毁类对象?

int SomeClass::function() {   
    int res = pthread_mutex_lock(&_mutex);
    if(res < 0)
        throw std::runtime_error("lock failed: " + std::string(std::strerror(res)));
    // some code
    res = pthread_mutex_unlock(&_mutex);
    if(res < 0)
        throw std::runtime_error("unlock failed: " + std::string(std::strerror(res)));
    return something;
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

编辑:

vaiable_mutex是一个受保护的类成员(非静态),在构造函数中仅使用pthread_mutex_init(&_mutex, NULL)

Ser*_*eyA 5

pthread_mutex_unlock 肯定会失败的唯一情况是被解锁的互斥锁不是有效的互斥锁或互斥锁不属于您的线程。因此,如果两者都不是,则您不必担心,并且这两种情况都是应用程序错误 - 此时您可以抛出异常而不必担心互斥状态,您会遇到更大的问题。