如何处理 pthread_mutex_unlock() 错误
How to handle a pthread_mutex_unlock() error?
我正在开发一个线程安全类,也可以处理错误。我想知道如何处理来自函数 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绝对失败的唯一情况是解锁的互斥锁不是有效的互斥锁或互斥锁不归您的线程所有。因此,如果两者都不是这种情况,您不必担心,并且这两个条件都是应用程序错误 - 此时您可以抛出异常而不用担心互斥状态,您有更大的问题。
相关文章:
- 如何在没有死锁和/或争用的情况下正确使用 std::mutex C++?
- std::mutex 如何防止线程修改?
- DRD 报告"conflicting load" std::mutex::lock 上的错误
- 是否需要 mutex() 来安全地同时访问具有 2 个线程的数组的不同元素?
- std::atomic 和 std::mutex 的相对性能
- 如何解决"'mutex' in namespace 'std' does not name a type"?
- std::lock_guard 怎么可能比 std::mutex::lock() 更快?
- 当"std::lock_guard<std::mutex>"对象没有名称时的不同行为
- std::mutex::lock() 产生奇怪(和不必要的)ASM 代码
- 使用 std::mutex 保护环路
- std::mutex作为一个成员变量对多个线程来说是安全的吗
- std::shared_timed_mutex何时比std::mutex慢,以及何时(不)使用它
- <mutex> 使用 /clr 或 /clr:pure 编译时不支持
- std::mutex 的发布-获取可见性保证是否仅适用于关键部分?
- 死锁使用 std::mutex 来保护多个线程中的 cout
- 返回持有 std::mutex 锁的 RAII 容器类
- 在 C++11 线程中,std::mutex 对内存可见性有什么保证?
- 为什么std::mutex::unlock()不是noexcept
- 是否有任何惯用的显式使用mutex::lock()或unlock()
- PThread Mutex Lock & Unlock on Stack