pthread mutex 属性

本文详细介绍了pthread mutex的四种属性:NORMAL、ERRORCHECK、RECURSIVE和DEFAULT。NORMAL类型不检测死锁,可能导致程序卡住;ERRORCHECK提供错误检查,重复操作会返回错误;RECURSIVE允许同一线程多次加锁,但需要对应次数解锁;DEFAULT属性可能导致未定义行为。建议避免使用NORMAL和DEFAULT,而是选择ERRORCHECK和RECURSIVE以确保更好的错误处理和防止死锁。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mutex互斥锁有四种属性,分别是NORMAL, ERRORCHECK, RECURSIVE, DEFAULT,通过pthread_mutexattr_settype 对互斥锁进行属性设置。

PTHREAD_MUTEX_NORMAL

This type of mutex does not detect deadlock. A thread attempting to relock this mutex without first unlocking it shall deadlock. Attempting to unlock a mutex locked by a different thread results in undefined behavior. Attempting to unlock an unlocked mutex results in undefined behavior.

PTHREAD_MUTEX_ERRORCHECK

This type of mutex provides error checking. A thread attempting to relock this mutex without first unlocking it shall return with an error. A thread attempting to unlock a mutex which another thread has locked shall return with an error. A thread attempting to unlock an unlocked mutex shall return with an error.

PTHREAD_MUTEX_RECURSIVE

A thread attempting to relock this mutex without first unlocking it shall succeed in locking the mutex. The relocking deadlock which can occur with mutexes of type PTHREAD_MUTEX_NORMAL cannot occur with this type of mutex. Multiple locks of this mutex shall require the same number of unlocks to release the mutex before another thread can acquire the mutex. A thread attempting to unlock a mutex which another thread has locked shall return with an error. A thread attempting to unlock an unlocked mutex shall return with an error.

PTHREAD_MUTEX_DEFAULT

Attempting to recursively lock a mutex of this type results in undefined behavior. Attempting to unlock a mutex of this type which was not locked by the calling thread results in undefined behavior. Attempting to unlock a mutex of this type which is not locked results in undefined behavior. An implementation may map this mutex to one of the other mutex types.

由于 DEFAULT 与 NORMAL 属性有太多的未定义行为,所以应该尽可能的避免使用。NORMAL会导致死锁,并不会反回错误代码,因而程序会卡住。互斥锁默认属性为NORMAL。

ERRORCHECK 重复加锁,重复解锁都会返回错误代码,不会导致死锁。
RECURSIVE 允许同一线程进行N次加锁,但必须进行N次解锁才能释放这把锁。A线程Lock后,B线程再次LOCK的时候,发生死锁。(试验环境 Linux ubuntu 3.19.0-25-generic #26~14.04.1-Ubuntu)

综上,避免使用NORMAL与DEFAULT属性,显示的设置ERRORCHECK与RECURSIVE属性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值