*引用本文请注明来自 blog.csdn.net/wtz1985
所谓"锁",就是为了让自己独自占有空间,在自己没用完之前,不让别人来占用自己的资源.现在的操作系统,无论是WINDOWS,还是UNIX等其他操作系统.都采用多线程的环境.这极大提高了任务的执行速度,而且不会影响其他事务的执行.但是它们的执行是靠时间片的轮转的,如果某一个线程没有执行完,可它的时间片用完了,就会被挂起来,直到轮到它的下个时间片.假如继续让它们这么自由的,没有约束的执行命令,将会导致一种不可预见的结果,可该怎么解决呢?请看下面:
锁的引出,就是为了某一个线程在操作某一件事务时,独自占有其资源,并把自己琐起来,在自己没有把锁解开之前,别人只能等,不能抢,这就有效地控制了线程们不会因为时间片的作祟,而导致出现不可想象的结果.下面用代码简述一下锁是怎么实现的:
1、定义锁的接口。
- /*----- locker.h -------*/
- #ifndef _LOCKER_H
- #define _LOCKER_H
- struct _Locker;
- typedef struct _Locker Locker;
- typedef int (*LockerLockFunc)(Locker* thiz);
- typedef int (*LockerUnlockFunc)(Locker* thiz);
- typedef void (*LockerDestroyFunc)(Locker* thiz);
- struct _Locker
- {
- LockerLockFunc lock;
- LockerUnlockFunc unlock;
- LockerDestroyFunc locker_destroy;
- char priv[0];
- };
- static inline int locker_lock(Locker* thiz)
- {
- assert(thiz != NULL && thiz->lock != NULL);
- return thiz->lock;
- }
- static inline int locker_unlock(Locker* thiz)
- {
- assert(thiz != NULL && thiz->unlock != NULL);
- return thiz->unlock;
- }
- static inline void locker_destroy(Locker* thiz)
- {
- assert(thiz != NULL && thiz->locker_destroy != NULL);
- return thiz->destroy_locker;
- }
- #endif /*_LOCKER_H*/
2、定义线程锁的接口。
- /*------ pthread_locker.h --------*/
- #ifndef _PTHREAD_LOCKER_H
- #define _PTHREAD_LOCKER_H
- #include "locker.h"
- Locker* locker_create(const char* name);
- #endif /*_PTHREAD_LOCKER_H*/
3、接口的实现。
- /*----- pthread_locker.c ------*/
- #include "pthread_locker.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <assert.h>
- typedef struct _PrivInfo
- {
- char* str_name;
- pthread_mutex_t mutex;
- }PrivInfo;
- static pthread_locker_lock(Locker* thiz)
- {
- assert(thiz != NULL);
- PrivInfo* priv = (PrivInfo*)thiz->priv;
- return pthread_mutex_lock(&(priv->mutex));
- }
- static pthread_locker_unlock(Locker* thiz)
- {
- assert(thiz != NULL);
- PrivInfo* priv = (PrivInfo*)thiz->priv;
- return pthread_mutex_unlock(&(priv->mutex));
- }
- static pthread_locker_destroy(Locker* thiz)
- {
- assert(thiz != NULL);
- PrivInfo* priv = (PrivInfo*)thiz->priv;
- free(priv->str);
- pthread_mutex_destroy(&(priv->mutex));
- free(thiz);
- return;
- }
- Locker* locker_create(const char* name)
- {
- Locker* thiz = (Locker*)malloc(sizeof(Locker)+sizeof(PrivInfo));
- PrivInfo* priv = thiz->priv;
- priv->str_name = strdup(name);
- pthread_mutex_init(&(priv->mutex), NULL);
- thiz->lock = pthread_locker_lock;
- thiz->unlock = pthread_lokcer_unlock;
- thiz->locker_destroy = pthread_locker_destroy;
- return thiz;
- }
这就是线程锁的简单实现。可是当你在链表中插入时,要进行查找的操作,这时候只是简单的线程锁是不能解决的,那该怎么解决呢?这就涉及到递归锁的问题咯,下一篇再说递归琐的实现。