递归锁

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

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

执行结果为:

this is a thread !
this is a test!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值