前言
本文章主要介绍线程同步中的互斥量。
一、互斥量
互斥量本质上是一把锁,在访问共享资源前对互斥量进行加锁,在访问完后释放互斥量。
#include <pthread.h>
#include <time.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_destory(pthread_mutex_t *mutex);
int pthread_mutex_lock(pthread_mutex_t *mutex); //阻塞
int pthread_mutex_trylock(pthread_mutex_t *mutex);//非阻塞
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_timedlock(pthread_mutex_t *mutex, const struct timespec *restrict tsptr);//对互斥量设置加锁的时长,时间到了就不加锁了
二、互斥量使用
1.使用互斥量保护数据结构
代码如下(示例):
struct foo{
int f_count;
pthread_mutex_t f_lock;
int f_id;
};
struct foo *foo_alloc(int id)
{
struct foo *fp;
if((fp = malloc(sizeof(struct foo))) != NULL){
fp->f_count = 1;
fp->f_id = id;
if(pthread_mutex_init(&fp->f_lock,NULL) != 0){
free(fp);
return(NULL);
}
}
return fp;
}
void foo_hold(struct foo *fp)//add
{
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
void foo_rele(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
if(--fp->f_count == 0){
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
}else{
pthread_mutex_unlock(&fp->f_lock);
}
}
2.pthread_mutex_timedlock设置加锁时间
代码如下(示例):
void unix_11_13_timedlock(void)
{
int err;
struct timespec tout;
struct tm *tmp;
char buf[64];
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&lock);
printf("mutex is lock\n");
clock_gettime(CLOCK_REALTIME,&tout);
tmp = localtime(&tout.tv_sec);
strftime(buf,sizeof(buf),"%r",tmp);
printf("current time is %s\n",buf);
tout.tv_sec += 10;
err = pthread_mutex_timedlock(&lock,&tout);
clock_gettime(CLOCK_REALTIME,&tout);
tmp = localtime(&tout.tv_sec);
strftime(buf,sizeof(buf),"%r",tmp);
printf("the time is now %s\n",buf);
if(err == 0)
printf("mutex locked again!\n");
else
printf("can't lock mutex again:%s\n",strerror(err));
exit(0);
}
程序故意对已经枷锁的互斥量加锁,为了说明pthread_mutex_timedlock是如何工作的。
代码结果: