pthread_mutex

pthread_mutex
int pthread_mutex_init(pthrad_mutex_t* mutex, const pthread_mutexatr_t* attr);
初始化互斥量mutex

int pthread_mutex_destory(pthread_mutex_t* mutex);
如果动态分配互斥量,那么在释放内存前,需要调用这个函数。

int pthread_mutex_lock(pthread_mutex_t* mutex);
对互斥量进行加锁。

int pthread_mutex_unlock(pthread_mutex_t* mutex);
对互斥量进行解锁。

int pthread_mutex_trylock(pthread_mutex_t* mutex);
不会出现阻塞。尝试对互斥量进行加锁,如果互斥量未被锁住,那么函数将锁住互斥量,并返回0,否则失败,不能锁住互斥量,返回EBUSY


 1  #include  < pthread.h >
 2  #include  < unistd.h >
 3  #include  < stdio.h >
 4  pthread_mutex_t mutex;
 5  int  val;
 6  void   * thread_run( void   * arg){
 7     // pthread_mutex_lock(&mutex);
 8     int  num  =   * (( int * )arg);
 9     if (num  %   2 ){
10      sleep( 2 );
11      printf( " thread_run --> num:%d, val:%d\n " , num, val);
12    }
13     else {
14       ++ val;
15    }
16     // pthread_mutex_unlock(&mutex);
17    pthread_exit(( void   * ) 0 );
18  }
19 
20  int  main(){
21    val  =   0 ;
22     int  i  =   0 , para[ 10 ];
23    pthread_t tid[ 10 ];
24     if (pthread_mutex_init( & mutex,NULL)){
25      printf( " init mutex error " );
26       return   0 ;
27    }
28     for  (i  =   0 ; i  <   10 ++ i){
29      para[i]  =  i;
30       if (pthread_create( & tid[i], NULL, thread_run, ( void * )( & para[i]))){
31         return   0 ;
32      }
33    }
34     for (i  =   0 ; i  <   10 ++ i){
35      pthread_join(tid[i], NULL);
36    }
37     return   0 ;
38  }

同时启动10个线程,但是10个线程间没有同步的去读或者写val变量。

没加锁的输出如下:
thread_run  -->  num: 1 , val: 5
thread_run 
-->  num: 3 , val: 5
thread_run 
-->  num: 5 , val: 5
thread_run 
-->  num: 7 , val: 5
thread_run 
-->  num: 9 , val: 5

加锁输出如下:
thread_run  -->  num: 1 , val: 1
thread_run 
-->  num: 3 , val: 2
thread_run 
-->  num: 5 , val: 3
thread_run 
-->  num: 7 , val: 4
thread_run 
-->  num: 9 , val: 5





你可能感兴趣的:(pthread_mutex)