Pthread_mutex_t锁
来源:互联网 发布:淘宝排名突然下降 编辑:程序博客网 时间:2024/05/16 07:26
- 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);加锁,但是与2不一样的是当锁已经在使用的时候,返回为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;
- }
阅读全文
0 0
- pthread_mutex_t锁
- Pthread_mutex_t锁
- pthread_mutex_t锁
- 使用pthread_mutex_t锁
- linux 锁机制 pthread_mutex_t
- linuxc_线程锁pthread_mutex_t
- 线程锁-pthread_mutex_t
- 使用pthread_mutex_t锁的例子
- 使用pthread_mutex_t锁的例子
- 使用pthread_mutex_t锁的例子
- 使用pthread_mutex_t锁的例子
- 使用pthread_mutex_t锁的例子
- 使用pthread_mutex_t锁的例子
- linux中的C里面使用pthread_mutex_t锁
- linux中的C里面使用pthread_mutex_t锁
- linux中的C里面使用pthread_mutex_t锁
- pthread_mutex_t封装的读优先锁
- pthread_mutex_t封装
- MySQL 线程池内幕
- 简单实现Ajax异步上传文件
- leetcode--Count and Say
- re.findall
- 牛客刷题知识点总结
- Pthread_mutex_t锁
- 数据库Sharding的基本思想和切分策略
- Android 复制文本内容到系统剪贴板的最简单实践
- CSS布局
- 设计模式初探-解释器模式
- vmware12在centos7中配置静态ip
- iOS 报错 resource fork, Finder information, or similar detritus not allowed
- 在Spring Boot中使用Spring Session解决分布式会话共享问题
- UVA