递归锁

递归锁在同一线程 内起作用。

  1. //线程属性 
  2. #include    <stdio.h> 
  3. #include <stdlib.h> 
  4. #include <pthread.h> 
  5. pthread_mutex_t g_mutex; 
  6. void test_fun(void); 
  7. static void thread_init(void
  8.     //初始化锁的属性 
  9.     pthread_mutexattr_t attr; 
  10.     pthread_mutexattr_init(&attr); 
  11.     pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);//设置锁的属性为可递归 
  12.      
  13.     //设置锁的属性 
  14.     pthread_mutex_init(&g_mutex, &attr); 
  15.      
  16.     //销毁 
  17.     pthread_mutexattr_destroy(&attr); 
  18. //线程执行函数 
  19. void* thr_fun(void* arg) 
  20.     int ret; 
  21.     ret=pthread_mutex_lock(&g_mutex); 
  22.     if( ret!=0 ) 
  23.     { 
  24.         perror("thread  pthread_mutex_lock"); 
  25.         exit(1); 
  26.     } 
  27.     printf("this is a thread !/n"); 
  28.     test_fun(); 
  29.     ret=pthread_mutex_unlock(&g_mutex); 
  30.     if( ret!=0 ) 
  31.     { 
  32.         perror("thread  pthread_mutex_unlock"); 
  33.         exit(1); 
  34.     } 
  35.     return NULL; 
  36. //测试函数 
  37. void test_fun(void
  38.     int ret; 
  39.     ret=pthread_mutex_lock(&g_mutex); 
  40.     if( ret!=0 ) 
  41.     { 
  42.         perror("test pthread_mutex_lock"); 
  43.         exit(1); 
  44.     } 
  45.     printf("this is a test!/n"); 
  46.     ret=pthread_mutex_unlock(&g_mutex); 
  47.     if( ret!=0 ) 
  48.     { 
  49.         perror("test pthread_mutex_unlock"); 
  50.         exit(1); 
  51.     } 
  52.  
  53. int main(int argc, char *argv[]) 
  54.     int ret; 
  55.     thread_init(); 
  56.      
  57.     pthread_t tid; 
  58.     ret=pthread_create(&tid, NULL, thr_fun, NULL); 
  59.     if( ret!=0 ) 
  60.     { 
  61.         perror("thread  create"); 
  62.         exit(1); 
  63.     } 
  64.     pthread_join(tid, NULL); 
  65.     return 0; 

执行结果为:

this is a thread !
this is a test!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值