天天看點

pthread_mutex_lock的thread特性pthread_mutex_lock的thread特性

作者:[email protected]

部落格:blog.focus-linux.net linuxfocus.blog.chinaunix.net

微網誌:weibo.com/glinuxer

QQ技術群:4367710

前幾天寫了一段示例代碼,想說明一下可重入函數。是以我在一個函數中使用了pthread_mutex_lock,來說明一旦函數使用了鎖,就變成了不可重入的函數。

上面代碼很簡單,main函數調用hold_mutex來持有鎖。hold_mutex直到SIGALRM信号處理函數傳回後,才會釋放鎖和退出。同時,main利用alarm,在3秒後可以收到信号SIGALRM,而SIGALRM的信号處理函數也會調用hold_mutex。

這就保證了,在main線程持有鎖的過程中,通過信号處理機制,再次進入hold_mutex,來造成“死鎖”的場景。用以說明hold_mutex是不可重入的。

可是運作結果讓我很意外。。。

這是怎麼回事呢?為什麼在main拿到鎖以後,信号處理函數還是可以拿到鎖呢?我決定在這樣試一下,直接在hold_mutex中再次拿鎖。 代碼變成了下面這樣:

執行結果如下:

看到這樣的結果,我首先想到難道pthread_mutex_lock是遞歸鎖?但仔細想了想,又推翻了這個想法。遞歸鎖是一種特殊的鎖,不大可能會作為預設行為。

當我盯着pthread_mutex_lock這個名字,pthread這個關鍵字給我帶來了提示。這個鎖是否是跟線程相關呢?當該線程擁有了該鎖後,可以繼續上鎖呢?

重讀了一遍manual手冊,證明了自己的想法。 The mutex object referenced by mutex shall be locked by calling pthreadmutexlock(). If the mutex is already locked, the calling thread shall block until the mutex becomes available. This operation shall return with the mutex object referenced by mutex in the locked state with the calling thread as its owner.

最後一句與我猜測的結果一樣。雖然猜中了這個結果,但是我卻沒有一點興奮,因為做Linux程式員已經有六、七年了,居然剛發現pthread_mutex_lock的這個特性。

路漫漫其修遠兮,吾将上下而求索。

繼續閱讀