最近遇到一个奇怪的问题,开机时程序的定时器失效了。但是重启程序后又正常了。定时器的主要代码:
void BThost_initEvent(BThost_Event* event,unsigned char manual_reset/*,const TCHAR* Eventname*/)
{
event->is_set = FALSE;
event->is_pulse= FALSE ;
event->is_manual_reset= manual_reset;
pthread_mutex_init( &event->lock, NULL );
pthread_cond_init( &event->cond, NULL );
}
int BThost_WaitEvent(BThost_Event* event, unsigned long waittime_usec)
{
int ret = 0;
struct timeval tp;
struct timespec ts;
if ( FALSE == event->is_manual_reset )
event->is_set = FALSE;
pthread_mutex_lock( &event->lock );
if ( TRUE != event->is_set )
{
if(waittime_usec == 0xFFFFFFFF)
{
pthread_cond_wait( &event->cond, &event->lock);
ret = 0;
}
else
{
int usec = 0;
gettimeofday(&tp, NULL);
ts.tv_sec = tp.tv_sec;
usec = tp.tv_usec+waittime_usec;
if(usec > 1000000)
{
ts.tv_sec += (usec/1000000);
usec = usec % 1000000;
}
ts.tv_nsec = usec * 1000;
ret = pthread_cond_timedwait( &event->cond, &event->lock ,(const struct timespec *)&ts);
while(ret == 0 && TRUE != event->is_set)
{
ret = pthread_cond_timedwait( &event->cond, &event->lock ,(const struct timespec *)&ts);
}
}
}
pthread_mutex_unlock( &event->lock );
if( ret != 0 ) //timeout
return 0;
return 1;
}
程序就在上图pthread_cond_timedwait被阻塞,后来使用下列代码将系统时间打印出来
FILE *fp = popen("date","r");
fread(buff,1024,1,fp);
pclose(fp);
打印的结果如下:
系统时间从2021年变成了2005年。
修改方法:不用gettimeofday,改用clock_gettime
void BThost_initEvent(BThost_Event* event,unsigned char manual_reset/*,const TCHAR* Eventname*/)
{
event->is_set = FALSE;
event->is_pulse= FALSE ;
event->is_manual_reset= manual_reset;
pthread_mutex_init( &event->lock, NULL );
#if 0
pthread_cond_init( &event->cond, NULL );
#else
pthread_condattr_t attr;
pthread_condattr_init(&attr);
pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
pthread_cond_init(&event->cond, &attr);
#endif
}
int BThost_WaitEvent(BThost_Event* event, unsigned long waittime_usec)
{
int ret = 0;
#if 0
struct timeval tp;
#else
struct timespec tp;
#endif
struct timespec ts;
if ( FALSE == event->is_manual_reset )
event->is_set = FALSE;
pthread_mutex_lock( &event->lock );
if ( TRUE != event->is_set )
{
if(waittime_usec == 0xFFFFFFFF)
{
pthread_cond_wait( &event->cond, &event->lock);
ret = 0;
}
else
{
int usec = 0;
#if 0
gettimeofday(&tp, NULL);
ts.tv_sec = tp.tv_sec;
usec = tp.tv_usec+waittime_usec;
if(usec > 1000000)
{
ts.tv_sec += (usec/1000000);
usec = usec % 1000000;
}
ts.tv_nsec = usec * 1000;
#else
long nanoseconds;
clock_gettime(CLOCK_MONOTONIC, &tp);
nanoseconds = tp.tv_nsec + (waittime_usec*1000L);
ts.tv_sec = tp.tv_sec;
if(nanoseconds > 1000000000)
{
ts.tv_nsec = nanoseconds % 1000000000L;
ts.tv_sec += (nanoseconds / 1000000000L);
}
else
ts.tv_nsec = nanoseconds;
#endif
ret = pthread_cond_timedwait( &event->cond, &event->lock ,(const struct timespec *)&ts);
while(ret == 0 && TRUE != event->is_set)
{
ret = pthread_cond_timedwait( &event->cond, &event->lock ,(const struct timespec *)&ts);
}
}
}
pthread_mutex_unlock( &event->lock );
if( ret != 0 ) //timeout
return 0;
return 1;
}
?
|