我编写了一个测试程序,该程序创建了一个1毫秒的posix计时器。当单独运行该程序或使用GDB进行调试时,计时是准确的。然后,将测试程序放入我的项目代码中,当我运行我的项目程序时,计时器也是准确的,但是如果我使用GDB调试项目,则计时器的计时不正确。
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define CLOCKID CLOCK_REALTIME
timer_t timer_id;
int timer_thread_cnt = 0;
void timer_thread(union sigval v)
{
timer_thread_cnt++;
printf("timer thread count <%d>\n", timer_thread_cnt);
}
int start_timer(void)
{
struct sigevent evp;
int ret;
memset(&evp, 0, sizeof(struct sigevent));
evp.sigev_value.sival_int = 111; /* it can be passed into callback */
evp.sigev_notify = SIGEV_THREAD; /* The thread notifying way -- dispatch a new thread. */
evp.sigev_notify_function = &timer_thread; /* The thread address */
if (timer_create(CLOCKID, &evp, &timer_id) == 0) { /* create timer */
struct itimerspec it;
it.it_interval.tv_sec = 0;
it.it_interval.tv_nsec = 1000000;
it.it_value.tv_sec = 0;
it.it_value.tv_nsec = 1000000;
printf("timer start...");
if (timer_settime(timer_id, 0, &it, NULL) == -1) { /* if timer create success, start it */
printf("start timer failed!\n");
if (timer_delete(timer_id) == -1) {
printf("timer delete failed!\n");
}
return -1;
}
} else {
printf("fail to timer_create");
return -1;
}
return 0;
}
int main(void)
{
start_timer();
while(1){
sleep(1);
}
}
如果计时器未正确计时,则程序运行10s后,程序中变量timer_thread_cnt
的值约为2000。顺便说一句,如果时间为10ms,则不会有问题。有谁知道这个问题的可能原因是什么。