我有以下从 pthread_create 调用的函数。这个函数做了一些工作,设置一个定时器,做一些其他的工作,然后等待定时器到期,然后再次执行循环。但是,在计时器第一次运行时,它到期后程序退出,我不完全确定为什么。它不应该离开无限的while循环。主线程从该线程中不访问任何内容,反之亦然(目前)。
我的猜测是我可能没有正确设置线程,或者计时器没有正确调用处理函数。也许从线程更改 IDLE 全局变量会导致问题。
我想在没有信号的情况下调用处理程序,因此使用 SIGEV_THREAD_ID。无论如何,我在主线程中使用 SIGUSRx 信号。关于我在这里开始的任何想法可能有什么问题?
#ifndef sigev_notify_thread_id
#define sigev_notify_thread_id _sigev_un._tid
#endif
volatile sig_atomic_t IDLE = 0;
timer_t timer_id;
struct sigevent sev;
void handler() {
printf("Timer expired.\n");
IDLE = 0;
}
void *thread_worker() {
struct itimerspec ts;
/* setup the handler for timer event */
memset (&sev, 0, sizeof(struct sigevent));
sev.sigev_notify = SIGEV_THREAD_ID;
sev.sigev_value.sival_ptr = NULL;
sev.sigev_notify_function = handler;
sev.sigev_notify_attributes = NULL;
sev.sigev_signo = SIGRTMIN + 1;
sev.sigev_notify_thread_id = syscall(SYS_gettid);
/* setup "idle" timer */
ts.it_value.tv_sec = 55;
ts.it_value.tv_nsec = 0;
ts.it_interval.tv_sec = 0;
ts.it_interval.tv_nsec = 0;
if (timer_create(0, &sev, &timer_id) == -1) {
printf("timer_create failed: %d: %s\n", errno, strerror(errno));
exit(3);
}
while (1) {
// do work here before timer gets started that takes 5 seconds
while (IDLE); /* wait here until timer_id expires */
/* setup timer */
if (timer_settime(timer_id, 0, &ts, NULL) == -1) {
printf("timer_settime failed: %d\n", errno);
exit(3);
}
IDLE = 1;
// do work here while timer is running but that does not take 10 seconds
}
}