pthread_cond_timedwait

该函数用于在同时等待条件变量时提供超时功能,不过该函数的超时时间是一个绝对时间。
默认使用系统时间,这意味这,若修改系统时间,那么超时就不准确,有可能提前返回,也可能要几年才返回。
这在某些需求下会导致bug。

初始化方法:

 1 #include <stdio.h>                                                                 
 2 #include <stdlib.h>                                                                
 3 #include <string.h>                                                                
 4 #include <unistd.h>                                                                
 5 #include <pthread.h>
 6  
 7 int main()                                                                         
 8 {                                                                                  
 9     pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;                                 
10     pthread_condattr_t attr;                                                       
11     pthread_cond_t cond;                                                           
12     pthread_condattr_init(&attr);                                                  
13     pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);                             
14     pthread_cond_init(&cond, &attr);
15     struct timespec tv;                                                            
16     pthread_mutex_lock(&m);                                                        
17     do{                                                                            
18         clock_gettime(CLOCK_MONOTONIC, &tv);                                       
19         tv.tv_sec += 1;                                                            
20         pthread_cond_timedwait(&cond,&m,&tv);                                      
21         printf("heart beat\n");                                                    
22     }while(1);                                                                     
23     pthread_mutex_unlock(&m);                                                      
24     return 0;                                                                      
25 } 

另,提示,编译时加上 -l pthread 选项

posted on 2018-04-20 15:42  枝桠  阅读(1861)  评论(0编辑  收藏  举报

导航