linux中的C里面使用pthread_mutex_t锁
来源:互联网 发布:快牙zapya软件 编辑:程序博客网 时间:2024/04/29 16:49
linux下为了多线程同步,通常用到锁的概念。
posix下抽象了一个锁类型的结构:ptread_mutex_t。通过对该结构的操作,来判断资源是否可以访问。顾名思义,加锁(lock)后,别人就无法打开,只有当锁没有关闭(unlock)的时候才能访问资源。
它主要用如下5个函数进行操作。
1:pthread_mutex_init(pthread_mutex_t * mutex,const pthread_mutexattr_t *attr);
初始化锁变量mutex。attr为锁属性,NULL值为默认属性。
2:pthread_mutex_lock(pthread_mutex_t *mutex);加锁
3:pthread_mutex_tylock(pthread_mutex_t *mutex);测试加锁,当锁已经在使用的时候,返回为EBUSY,而不是挂起等待。
4:pthread_mutex_unlock(pthread_mutex_t *mutex);释放锁
5:pthread_mutex_destroy(pthread_mutex_t *mutex);使用完后释放
下面经典例子为创建两个线程对sum从1加到100。前面第一个线程从1-49,后面从50-100。主线程读取最后的加值。为了防止资源竞争,用了pthread_mutex_t 锁操作。
- #include<stdlib.h>
- #include<stdio.h>
- #include<unistd.h>
- #include<pthread.h>
- typedef struct ct_sum
- { int sum;
- pthread_mutex_t lock;
- }ct_sum;
- void * add1(void * cnt)
- {
- pthread_mutex_lock(&(((ct_sum*)cnt)->lock));
- int i;
- for( i=0;i<50;i++){
- (*(ct_sum*)cnt).sum+=i;}
- pthread_mutex_unlock(&(((ct_sum*)cnt)->lock));
- pthread_exit(NULL);
- return 0;
- }
- void * add2(void *cnt)
- {
- int i;
- cnt= (ct_sum*)cnt;
- pthread_mutex_lock(&(((ct_sum*)cnt)->lock));
- for( i=50;i<101;i++)
- { (*(ct_sum*)cnt).sum+=i;
- }
- pthread_mutex_unlock(&(((ct_sum*)cnt)->lock));
- pthread_exit(NULL);
- return 0;
- }
- int main(void)
- { int i;
- pthread_t ptid1,ptid2;
- int sum=0;
- ct_sum cnt;
- pthread_mutex_init(&(cnt.lock),NULL);
- cnt.sum=0;
- pthread_create(&ptid1,NULL,add1,&cnt);
- pthread_create(&ptid2,NULL,add2,&cnt);
- pthread_mutex_lock(&(cnt.lock));
- printf("sum %d\n",cnt.sum);
- pthread_mutex_unlock(&(cnt.lock));
- pthread_join(ptid1,NULL);
- pthread_join(ptid2,NULL);
- pthread_mutex_destroy(&(cnt.lock));
- return 0;
- }
- linux中的C里面使用pthread_mutex_t锁
- linux中的C里面使用pthread_mutex_t锁
- linux中的C里面使用pthread_mutex_t锁
- linux 锁机制 pthread_mutex_t
- 使用pthread_mutex_t锁
- linux互斥锁pthread_mutex_t 的使用
- Linux 互斥锁 pthread_mutex_t 的使用
- 使用pthread_mutex_t锁的例子
- 使用pthread_mutex_t锁的例子
- 使用pthread_mutex_t锁的例子
- 使用pthread_mutex_t锁的例子
- 使用pthread_mutex_t锁的例子
- 使用pthread_mutex_t锁的例子
- 【linux】pthread_mutex_t
- pthread_mutex_t锁
- Pthread_mutex_t锁
- pthread_mutex_t锁
- C语言互斥锁pthread_mutex_t
- TCHAR与C语言string.h的对应关系
- 初学试试看cocos2dx的TestCPP框架(10)---TouchesTest
- 设计模式综合实例分析之数据库同步系统(一)
- 第一次负责项目的总结
- 读后感:Mao: a biography-- 时势造英雄
- linux中的C里面使用pthread_mutex_t锁
- (国)电磁放面的内容 第一二章
- IOC框架
- final_抽象类_模版模式_接口
- 安装ubuntu
- objective-c callbacks
- Struts2学习笔记——文件上传技术
- 物以稀为贵
- Mathtype公式与文档文字对齐