linux 线程挂起恢复的简单示例

  1. #include <unistd.h>  
  2. #include <pthread.h>  
  3.   
  4. static pthread_mutex_t mutex;  
  5. static pthread_cond_t cond;  
  6. static int flag = 0;  
  7.   
  8. void srpthread_init()  
  9. {  
  10.     pthread_mutex_init(&mutex,NULL);  
  11.     pthread_cond_init(&cond,NULL);  
  12. }  
  13.   
  14. void srpthread_suspend()  
  15. {  
  16.     pthread_mutex_lock(&mutex);  
  17.     flag--;  
  18.     pthread_mutex_unlock(&mutex);  
  19. }  
  20.   
  21.   
  22. void srpthread_resume()  
  23. {  
  24.     pthread_mutex_lock(&mutex);  
  25.     flag++;  
  26.     pthread_cond_signal(&cond);  
  27.     pthread_mutex_unlock(&mutex);  
  28. }  
  29.   
  30. void *thread_run()  
  31. {  
  32.     while(1)  
  33.     {  
  34.         pthread_mutex_lock(&mutex);  
  35.         while(flag<=0)  
  36.         {  
  37.             pthread_cond_wait(&cond,&mutex);  
  38.         }  
  39.   
  40.         pthread_mutex_unlock(&mutex);  
  41.   
  42.         //actual work  
  43.         printf("i am running!\n");  
  44.     }  
  45.   
  46. }  
  47.   
  48. int main(int argc,char *argv[])  
  49. {  
  50.     char ch;  
  51.     pthread_t p1;  
  52.     srpthread_init();  
  53.     pthread_create(&p1,NULL,(void *)thread_run,NULL);  
  54.   
  55.     while(1)  
  56.     {  
  57.         scanf("%c",&ch);  
  58.         switch(ch)  
  59.         {  
  60.             case 's':  
  61.                 srpthread_suspend();  
  62.                 break;  
  63.             case 'r':  
  64.                 srpthread_resume();  
  65.                 break;  
  66.             default:  
  67.                 break;  
  68.         }  
  69.     }  
  70. #if 0  
  71.     printf("1111\n");  
  72.     srpthread_resume();  
  73.     printf("2222\n");  
  74.     sleep(3);  
  75.     printf("3333\n");  
  76.     srpthread_suspend();  
  77.     printf("4444\n");  
  78. #endif  
  79.     return 1;  
  80. }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值