linux中的C里面使用pthread_mutex_t锁

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 锁操作。

  1. #include<stdlib.h>  
  2. #include<stdio.h>  
  3. #include<unistd.h>  
  4. #include<pthread.h>  
  5. typedef struct ct_sum  
  6. {   int sum;  
  7.     pthread_mutex_t lock;  
  8. }ct_sum;  
  9. void * add1(void * cnt)  
  10. {       
  11.      
  12.     pthread_mutex_lock(&(((ct_sum*)cnt)->lock));  
  13.     int i;  
  14.         for( i=0;i<50;i++){  
  15.             (*(ct_sum*)cnt).sum+=i;}  
  16.     pthread_mutex_unlock(&(((ct_sum*)cnt)->lock));  
  17.     pthread_exit(NULL);  
  18.     return 0;  
  19. }  
  20. void * add2(void *cnt)  
  21. {       
  22.     int i;  
  23.     cnt= (ct_sum*)cnt;  
  24.     pthread_mutex_lock(&(((ct_sum*)cnt)->lock));  
  25.     for( i=50;i<101;i++)  
  26.     {    (*(ct_sum*)cnt).sum+=i;         
  27.     }  
  28.     pthread_mutex_unlock(&(((ct_sum*)cnt)->lock));  
  29.     pthread_exit(NULL);  
  30.     return 0;  
  31. }  
  32. int main(void)  
  33. {   int i;  
  34.     pthread_t ptid1,ptid2;  
  35.     int sum=0;  
  36.     ct_sum cnt;  
  37.     pthread_mutex_init(&(cnt.lock),NULL);  
  38.     cnt.sum=0;  
  39.     pthread_create(&ptid1,NULL,add1,&cnt);  
  40.     pthread_create(&ptid2,NULL,add2,&cnt);  
  41.   
  42.     pthread_mutex_lock(&(cnt.lock));  
  43.     printf("sum %d\n",cnt.sum);  
  44.     pthread_mutex_unlock(&(cnt.lock));  
  45.     pthread_join(ptid1,NULL);  
  46.     pthread_join(ptid2,NULL);  
  47.     pthread_mutex_destroy(&(cnt.lock));  
  48.     return 0;  
  49. }   
  50.    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值