转自:http://blog.csdn.net/wtz1985/article/details/3016375
在上一篇文章中,我已经阐述了多线程中简单锁的实现,可在结束的时候,我就提了那么一个问题,那就是如果在一个链表中进行插入时,要进行查询的操作,如果只是简单的锁,是没法实现的。所以“递归锁”就浮现于世了。
可能有些人看到递归这两个字,有点傻了眼,其实也没什么的,简单的介绍,就是进行简单的计数而已。刚开始引用锁的时候,就产生它,当在锁没有解开的时候,还要继续用锁,就简单的加一,解开一把就减一,当计数为零时,就把锁销毁掉。下面用程序来简单的阐述一下,递归锁是怎么实现的:
1、递归锁接口的定义。(锁的接口的定义已经在上一篇定义过了,这里不再重复)
-
-
- #ifndef _RECURSIVE_H
- #define _RECURSIVE_H
-
- #include "locker.h"
-
- Locker* recursive_locker_create(Locker* real_locker);
-
- #endif /*_RECURSIVE_H*/
2、递归锁的实现。
-
-
- #include "recursive_locker.h"
- #include <stdlib.h>
- #include <stdio.h>
- #include <assert.h>
- #include <string.h>
-
- typedef struct _PrivInfo
- {
- Locker* real_locker;
- pthread_t current_pthread_locker;
- int locker_count;
- }PrivInfo;
-
- static int recursive_locker_lock(Locker* thiz)
- {
- assert(thiz != NULL);
-
- PrivInfo* priv = thiz->priv;
- if(priv->current_pthread_locker == pthread_self())
- {
- priv->locker_count ++;
- }
- else
- {
-
- locker_lock(priv->real_locker);
- priv->lcoker_count = 1;
- priv->current_pthread_locker = pthread_self();
- }
-
- return 0;
- }
-
- static int recursive_locker_unlock(Locker* thiz)
- {
- assert(thiz != NULL);
-
- PrivInfo* priv = thiz->priv;
- if(priv->current_>pthread_locker == pthread_self())
- {
- if(priv->locker_count == 1)
- {
- priv->locker_count = 0;
- priv->current_pthread_locker = 0;
- locker_unlock(priv->real_locker);
- }
- else
- {
- priv->locker_count --;
- }
- }
- else
- {
- assert(!"error");
- }
-
- return 0;
- }
-
- static void recursive_locker_destroy(Locker* thiz)
- {
- assert(thiz != NULL);
-
- PrivInfo* priv = thiz->priv;
- locker_destroy(priv->real_locker);
- free(thiz);
-
- return ;
- }
-
- Locker* recursive_locker_create(Locker* real_locker)
- {
- Locker* thiz = (Locker* )malloc(sizeof(Locker) + sizeof(PrivInfo));
- PrivInfo* priv = thiz->priv;
- priv->real_locker = real_locker;
- priv->current_pthread_locker = 0;
- priv->locker_count = 0;
-
- thiz->lock = recursive_locker_lock;
- thiz->unlock = recursive_locker_unlock;
- thiz->locker_destroy = recursive_locker_destroy;
-
- return thiz;
- }
上面就是递归锁的实现。如果对COM熟悉的话,这个递归锁结构应该是比较简单的,就是一个的计数器而已。有了这个递归锁就不用愁在链表插入的时候,在进行查询操作锁会出现问题。