如何处理 pthread_mutex_unlock() 错误

How to handle a pthread_mutex_unlock() error?

本文关键字:mutex unlock 错误 何处理 pthread 处理      更新时间:2023-10-16

我正在开发一个线程安全类,也可以处理错误。我想知道如何处理来自函数 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;
}

谢谢!

编辑:

可用_mutex是在构造函数中仅使用pthread_mutex_init(&_mutex, NULL)初始化的受保护类成员(非静态)

pthread_mutex_unlock绝对失败的唯一情况是解锁的互斥锁不是有效的互斥锁或互斥锁不归您的线程所有。因此,如果两者都不是这种情况,您不必担心,并且这两个条件都是应用程序错误 - 此时您可以抛出异常而不用担心互斥状态,您有更大的问题。