pthread_cond_timedwait立即返回ETIMEDOUT

fgs*_*gts 0 c c++ multithreading posix pthreads

我试图用pthread_cond_timedwait等待Java的超时等待wait(long timeout, int nanos).我知道Java wait使用相对超时,而pthread_cond_timedwait使用绝对时间阈值.尽管考虑到这一点,pthread_cond_timedwait似乎立即返回错误代码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;
}
Run Code Online (Sandbox Code Playgroud)

Mil*_*nek 7

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

pthread_condattr_t condattr;
pthread_condattr_init(&condattr);
pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC);
pthread_cond_init(&cond, &condattr);
Run Code Online (Sandbox Code Playgroud)