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

[cpp] view plaincopyprint?
  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.    
原创粉丝点击