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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章