我有以下从 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
}
}
最佳答案
据我所知,您还没有为 SIGUSR1
安装信号处理程序,因此通过默认操作,它会在执行操作时杀死进程。
无论如何,整件事让我觉得设计非常糟糕:
while 循环将在等待计时器到期时为您提供 100% 的 CPU 负载。
这不是您使用
SIGEV_THREAD_ID
的方式,事实上SIGEV_THREAD_ID
并未真正设置为可供应用程序使用。相反,它是供 libc 在内部使用来实现SIGEV_THREAD
。你真的不想使用信号。它们很乱。
如果你有线程,为什么不在循环中调用clock_nanosleep
?当你无法做到这一点时,计时器主要有用,例如当你不能使用线程时。
关于c - timer_settime 在 uClinux 上的 pthread 中调用处理函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25355125/