免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 900 | 回复: 0
打印 上一主题 下一主题

Linux多线程同步—mutex [复制链接]

论坛徽章:
1
15-16赛季CBA联赛之北控
日期:2022-03-04 22:35:50
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-04-30 22:47 |只看该作者 |倒序浏览

作者: YpoClose  出自: http://www.linuxdiyf.com
1. 初始化:
在Linux下, 线程的互斥量数据类型是pthread_mutex_t. 在使用前, 要对它进行初始化:
对于静态分配的互斥量, 可以把它设置为PTHREAD_MUTEX_INITIALIZER, 或者调用pthread_mutex_init.
对于动态分配的互斥量, 在申请内存(malloc)之后, 通过pthread_mutex_init进行初始化, 并且在释放内存(free)前需要调用pthread_mutex_destroy.
原型:
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restric attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
头文件:
返回值: 成功则返回0, 出错则返回错误编号.
说明: 如果使用默认的属性初始化互斥量, 只需把attr设为NULL. 其他值在以后讲解.
2. 互斥操作:
对共享资源的访问, 要对互斥量进行加锁, 如果互斥量已经上了锁, 调用线程会阻塞, 直到互斥量被解锁. 在完成了对共享资源的访问后, 要对互斥量进行解锁.
首先说一下加锁函数:
头文件:
原型:
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
返回值: 成功则返回0, 出错则返回错误编号.
说明: 具体说一下trylock函数, 这个函数是非阻塞调用模式, 也就是说, 如果互斥量没被锁住, trylock函数将把互斥量加锁, 并获得对共享资源的访问权限; 如果互斥量被锁住了, trylock函数将不会阻塞等待而直接返回EBUSY, 表示共享资源处于忙状态.
再说一下解所函数:
头文件:
原型: int pthread_mutex_unlock(pthread_mutex_t *mutex);
返回值: 成功则返回0, 出错则返回错误编号.
3. 死锁:
死锁主要发生在有多个依赖锁存在时, 会在一个线程试图以与另一个线程相反顺序锁住互斥量时发生. 如何避免死锁是使用互斥量应该格外注意的东西.
总体来讲, 有几个不成文的基本原则:
对共享资源操作前一定要获得锁.
完成操作以后一定要释放锁.
尽量短时间地占用锁.
如果有多锁, 如获得顺序是ABC连环扣, 释放顺序也应该是ABC.
线程错误返回时应该释放它所获得的锁.
谈了这么多就让我举个实际点的例子来说明以上函数的功能:
(代码来源于:《GPRS服务器Linux编程》作者:李杨明)
CODE:
#include
#include
#include
#include
#include
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int lock_var;
time_t end_time;
int sum;
void pthread1(void *arg);
void pthread2(void *arg);
void pthread3(void *arg);
int main(int argc, char *argv[])
{
pthread_t id1,id2,id3;
pthread_t mon_th_id;
int ret;
sum=10;
end_time = time(NULL)+10;
pthread_mutex_init(&mutex,NULL);
ret=pthread_create(&id1,NULL,(void *)pthread1, NULL);
if(ret!=0)
perror("pthread cread1");
ret=pthread_create(&id2,NULL,(void *)pthread2, NULL);
if(ret!=0)
perror("pthread cread2");
ret=pthread_create(&id3,NULL,(void *)pthread3, NULL);
if(ret!=0)
perror("pthread cread3");
pthread_join(id1,NULL);
pthread_join(id2,NULL);
pthread_join(id3,NULL);
exit(0);
}
void pthread1(void *arg)
{
int i;
while(time(NULL)

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/31/showart_653660.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP