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

原文:http://blog.csdn.net/lllxy/article/details/3874415

[c-sharp]  view plain copy
  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");  
  44. }  
使用pthread_cond_timedwait把一个线程作为一个定时器使用.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然可以,下面是一个使用pthread_cond_timedwait函数的示例: ```c #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <time.h> // 全局变量和互斥锁、条件变量 int count = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; // 线程函数,等待并增加count void* thread_func(void* arg) { pthread_mutex_lock(&mutex); struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += 3; // 设置等待时间为3秒 // 等待条件满足或超时 int ret = pthread_cond_timedwait(&cond, &mutex, &ts); if (ret == ETIMEDOUT) { printf("Wait timed out.\n"); } else if (ret == 0) { printf("Count is %d\n", count); count++; } else { printf("Wait failed.\n"); } pthread_mutex_unlock(&mutex); return NULL; } int main() { pthread_t thread; pthread_create(&thread, NULL, thread_func, NULL); sleep(1); // 等待子线程启动 pthread_mutex_lock(&mutex); count = 42; // 设置count的值 pthread_cond_signal(&cond); // 发送条件信号 pthread_mutex_unlock(&mutex); pthread_join(thread, NULL); return 0; } ``` 在此示例中,我们使用了pthread_cond_timedwait函数来等待条件满足或超时。主线程设置了一个初始值为42的count,并发送一个条件信号,子线程在等待条件满足后打印出当前的count值。如果超过了等待时间3秒,则子线程会打印出"Wait timed out."的消息。 希望这个示例能够帮助到你!如果你还有其他问题,请随时问我。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值