大龙的博客

常用链接

统计

最新评论

使用pthread_cond_timedwait把一个线程作为一个定时器使用. --- 转

 
[c-sharp] view plaincopy
  1. #include <pthread.h>  
  2. #include <stdio.h>  
  3. #include <unistd.h>  
  4. #include <stdlib.h>  
  5. void * Proc(void * arg)  
  6. {  
  7.    pthread_cond_t cond;  
  8.    pthread_mutex_t mutex;  
  9.   
  10.     pthread_mutex_init(&mutex,NULL);  
  11.     pthread_cond_init(&cond,NULL);  
  12.   
  13.    timespec to;  
  14.   
  15.     int i = 0;  
  16.     pthread_mutex_lock(&mutex);  
  17.     to.tv_sec = time(NULL) + 3;  
  18.     to.tv_nsec = 0;  
  19.     while (i < 5)   
  20.     {  
  21.   
  22.         int err = pthread_cond_timedwait(&cond, &mutex, &to);  
  23.         if (err == ETIMEDOUT)   
  24.         {  
  25.              printf("time out %d: dispatch something.../n",i);  
  26.          i++;  
  27.         }  
  28.   
  29.     }  
  30.   
  31.      pthread_mutex_unlock(&mutex);  
  32.   
  33.   
  34. }  
  35. int main()  
  36. {      
  37.     pthread_t pid;  
  38.     int i=0;  
  39.     printf("create thread.../n");  
  40.     pthread_create(&pid,0,Proc,0);  
  41.     pthread_join(pid,NULL);  
  42.     sleep(1);  
  43.     printf("Succeed exit!/n");  

posted on 2013-02-17 19:42 大龙 阅读(5113) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理