unix环境高级编程-互斥量机制

1.互斥量是干嘛的?

 解决线程同步问题的方案之一

2.互斥量接口

互斥量的数据类型表示:pthread_mutex_t

使用互斥变量之前,必须首先对它进行初始化

    #include <pthread.h>  
    int pthread_mutex_init (pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);  
    int pthread_mutex_destroy (pthread_mutex_t *mutex);  
                                                  返回值:若成功则返回0,否则返回错误编号  

对互斥量进行加锁,需要调用pthread_mutex_lock。如果互斥量已经上锁,调用线程将阻塞直到互斥量被解锁。

#include <pthread.h>  
int pthread_mutex_trylock (pthread_mutex_t *mutex);  
  
int pthread_mutex_lock (pthread_mutex_t *mutex);  
  
int pthread_mutex_unlock (pthread_mutex_t *mutex);  
                                        返回值:若成功则返回0,否则返回错误编号  

对互斥量进行加锁,需要调用pthread_mutex_lock,如果互斥量已经上锁,调用线程将阻塞直到互斥量被解锁。对互斥量解锁需要调用pthread_mutex_unlock。    如果线程不希望被阻塞,它可以使用pthread_mutex_trylock尝试对互斥量进行加锁。如果调用pthread_mutex_tyrlock时互斥量处于未加锁状态,那么pthread_mutex_trylock将锁住互斥量,不会出现阻塞并返回0,否则pthread_muxte_trylock就会失败,不能锁住互斥量,而返回EBUSY。


3.死锁问题

常见产生死锁的情况:

1.线程试图对同一互斥量加锁两次

2.程序中使用一个以上的互斥量时,如果允许一个线程一直占有第一个互斥量,并且在试图锁住第二个互斥量时处于阻塞状态,但拥有第二个互斥量的线程也在试图锁住第一个互斥量。

死锁问题将会专门讨论,此处我们把重点放在互斥量的介绍上。


4.pthread_mutex_timedlock函数

    #include <pthread.h>  
    #include <time.h>  
    int pthread_mutex_timedlock(pthread_mutex_t mutex, const struct timespec *tsptr);  

 当程序试图获取一个已加锁的互斥量时,pthread_mutex_timedlock互斥量原语允许绑定线程阻塞时间。pthread_mutex_timedlock函数与pthread_mutex_lock函数是基本等价的,但是在达到超时时间时,pthread_mutex_timedlock不会对互斥量进行加锁,而是返回错误码ETIMEOUT.


5.代码实例

(1)使用互斥量保护数据结构

#include <stdlib.h>
#include <pthread.h>

struct foo {
	int             f_count;
	pthread_mutex_t f_lock;
	int             f_id;
	/* ... more stuff here ... */
};

struct foo *
foo_alloc(int id) /* allocate the object */
{
	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);
		}
		/* ... continue initialization ... */
	}
	return(fp);
}

void
foo_hold(struct foo *fp) /* add a reference to the object */
{
	pthread_mutex_lock(&fp->f_lock);
	fp->f_count++;
	pthread_mutex_unlock(&fp->f_lock);
}

void
foo_rele(struct foo *fp) /* release a reference to the object */
{
	pthread_mutex_lock(&fp->f_lock);
	if (--fp->f_count == 0) { /* last reference */
		pthread_mutex_unlock(&fp->f_lock);
		pthread_mutex_destroy(&fp->f_lock);
		free(fp);
	} else {
		pthread_mutex_unlock(&fp->f_lock);
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五癫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值