pthread_cond_timedwait returns ETIMEDOUT 立即

pthread_cond_timedwait returns ETIMEDOUT immediately

我正在尝试使用 pthread_cond_timedwait 来等待超时,类似于 Java 的 wait(long timeout, int nanos)。我知道 Java 的 wait 使用相对超时,而 pthread_cond_timedwait 使用绝对时间阈值。尽管考虑到这一点,pthread_cond_timedwait 立即出现 return,错误代码为 ETIMEDOUT。

下面的示例程序打印出一个 <0 的值。我希望它打印一个值 >=0.

我使用 pthread_cond_timedwait 不正确吗?我将如何重写下面的程序以添加例如延迟5 秒?

#define _POSIX_C_SOURCE 199309L

#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <errno.h>

int main(void) {
    pthread_mutex_t mutex;
    pthread_cond_t cond;

    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    pthread_mutex_lock(&mutex);

    struct timespec t1;
    struct timespec t2;

    clock_gettime(CLOCK_MONOTONIC, &t1);

    t1.tv_sec += 5;

    while(pthread_cond_timedwait(&cond, &mutex, &t1) != ETIMEDOUT);

    clock_gettime(CLOCK_MONOTONIC, &t2);

    printf("%d", t2.tv_sec - t1.tv_sec);

    pthread_mutex_unlock(&mutex);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    return 0;
}

你用错了时钟。 pthread_cond_timedwait 使用的默认时钟是 CLOCK_REALTIME。如果你真的想使用 CLOCK_MONOTONIC,你需要设置你的条件变量的时钟属性:

pthread_condattr_t condattr;
pthread_condattr_init(&condattr);
pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC);
pthread_cond_init(&cond, &condattr);