0

我有以下从 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
    }
}
4

1 回答 1

1

据我所知,您还没有为 安装信号处理程序SIGUSR1,因此默认操作会在执行该操作时终止该进程。

无论如何,整件事让我觉得设计非常糟糕:

  1. while 循环将在等待计时器到期时为您提供 100% 的 cpu 负载。

  2. 这不是您使用的方式SIGEV_THREAD_ID,实际上SIGEV_THREAD_ID并没有真正设置为可供应用程序使用。而是让 libc 在内部使用来实现SIGEV_THREAD.

  3. 你真的不想使用信号。他们很乱。

如果您有线程,为什么不只是clock_nanosleep循环调用?计时器主要在您不能这样做时有用,例如当您不能使用线程时。

于 2014-08-18T03:29:35.237 回答