博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
unix环境高级编程-互斥量机制
阅读量:4213 次
发布时间:2019-05-26

本文共 2253 字,大约阅读时间需要 7 分钟。

1.互斥量是干嘛的?

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

2.互斥量接口

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

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

#include 
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 
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 
#include
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 
#include
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);}voidfoo_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);}voidfoo_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); }}

转载地址:http://wiumi.baihongyu.com/

你可能感兴趣的文章
JVM垃圾回收相关知识笔记
查看>>
Curator学习笔记(一)- 读写锁
查看>>
第一次炒股小记
查看>>
《redis in action》ZSet相关命令
查看>>
《redis in action》redis发布订阅
查看>>
《redis in action》sort排序命令
查看>>
《redis in action》redis事务
查看>>
《redis in action》key的自动过期
查看>>
《redis in action》redis持久化简介
查看>>
Oracle RAC Failover 详解
查看>>
批处理 自动修改 IP 地址
查看>>
Oracle RAC LoadBalance
查看>>
v$sql,v$sqlarea,v$sqltext 和 v$sql_plan 说明
查看>>
ORA-31623 When Submitting a Datapump Job [ID 308388.1]
查看>>
Oracle SYSAUX 表空间 说明
查看>>
RAC 安装patch 后启动实例 报错 ORA-00439 feature not enabled- Real Application Clusters 解决方法
查看>>
On RAC, expdp Removes the Service Name [ID 1269319.1]
查看>>
Important Changes to Oracle Database Patch Sets Starting With 11.2.0.2 [ID 1189783.1]
查看>>
Oracle RAC 平台下 Patch 安装与卸载 步骤
查看>>
Oracle Database 11gR1 和 10gR2 ASM Best Practices 说明文档
查看>>