1. 程式人生 > >多執行緒中遞迴鎖的實現.

多執行緒中遞迴鎖的實現.

*引用本文請註明來自 blog.csdn.net/wtz1985       

在上一篇文章中,我已經闡述了多執行緒中簡單鎖的實現,可在結束的時候,我就提了那麼一個問題,那就是如果在一個連結串列中進行插入時,要進行查詢的操作,如果只是簡單的鎖,是沒法實現的。所以“遞迴鎖”就浮現於世了。

可能有些人看到遞迴這兩個字,有點傻了眼,其實也沒什麼的,簡單的介紹,就是進行簡單的計數而已。剛開始引用鎖的時候,就產生它,當在鎖沒有解開的時候,還要繼續用鎖,就簡單的加一,解開一把就減一,當計數為零時,就把鎖銷燬掉。下面用程式來簡單的闡述一下,遞迴鎖是怎麼實現的:

1、遞迴鎖介面的定義。(鎖的介面的定義已經在上一篇定義過了,這裡不再重複)

  1. /*------ recursive_locker.h -------*/
  2. #ifndef _RECURSIVE_H
  3. #define _RECURSIVE_H
  4. #include "locker.h"
  5. Locker* recursive_locker_create(Locker* real_locker);
  6. #endif /*_RECURSIVE_H*/

2、遞迴鎖的實現。

  1. /*------ recursive_locker.c ------*/
  2. #include "recursive_locker.h"
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <assert.h>
  6. #include <string.h>
  7. typedef struct _PrivInfo
  8. {
  9.   Locker*  real_locker;
  10.   pthread_t current_pthread_locker;
  11. int locker_count;
  12. }PrivInfo;
  13. staticint recursive_locker_lock(Locker* thiz)
  14. {
  15.   assert(thiz != NULL);
  16.   PrivInfo* priv = thiz->priv;
  17. if(priv->current_pthread_locker == pthread_self())
  18.   {
  19.     priv->locker_count ++;
  20.   }
  21. else
  22.   {
  23.     locker_lock(priv->real_locker);
  24.     priv->lcoker_count = 1;
  25.     priv->current_pthread_locker = pthread_self();
  26.   }
  27. return 0;
  28. }
  29. staticint recursive_locker_unlock(Locker* thiz)
  30. {
  31.   assert(thiz != NULL);
  32.   PrivInfo* priv = thiz->priv;
  33. if(priv->current_>pthread_locker == pthread_self())
  34.   {
  35. if(priv->locker_count == 1)
  36.     {
  37.       priv->locker_count = 0;
  38.       priv->current_pthread_locker = 0;
  39.       locker_unlock(priv->real_locker);
  40.     }
  41. else
  42.     {
  43.     priv->locker_count --;
  44.     }
  45.   }
  46. else
  47.   {
  48.      assert(!"error");
  49.   }
  50. return 0;
  51. }
  52. staticvoid recursive_locker_destroy(Locker* thiz)
  53. {
  54.   assert(thiz != NULL);
  55.   PrivInfo* priv = thiz->priv;
  56.   locker_destroy(priv->real_locker);
  57.   free(thiz);
  58. return ;
  59. }
  60. Locker* recursive_locker_create(Locker* real_locker)
  61. {
  62.   Locker* thiz = (Locker* )malloc(sizeof(Locker) + sizeof(PrivInfo));
  63.   PrivInfo* priv = thiz->priv;
  64.   priv->real_locker = real_locker;
  65.   priv->current_pthread_locker = 0;
  66.   priv->locker_count = 0;
  67.   thiz->lock = recursive_locker_lock;
  68.   thiz->unlock = recursive_locker_unlock;
  69.   thiz->locker_destroy = recursive_locker_destroy;
  70. return thiz;
  71. }

上面就是遞迴鎖的實現。如果對COM熟悉的話,這個遞迴鎖結構應該是比較簡單的,就是一個的計數器而已。有了這個遞迴鎖就不用愁在連結串列插入的時候,在進行查詢操作鎖會出現問題。