pthread mutex 属性

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属性。

你可能感兴趣的:(线程,pthread)