zoukankan      html  css  js  c++  java
  • 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
    ");                                                    
    22     }while(1);                                                                     
    23     pthread_mutex_unlock(&m);                                                      
    24     return 0;                                                                      
    25 } 

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

  • 相关阅读:
    03 http请求协议与响应协议
    02 web应用程序
    Django web框架目录
    01 http协议
    Django框架
    Bootstrap栅格系统
    bootstrap介绍和引入
    Python中日志logging模块
    Python 装饰器实现单列模式
    Python 如何理解可更改元组中的可变序列
  • 原文地址:https://www.cnblogs.com/fallenmoon/p/8891218.html
Copyright © 2011-2022 走看看