简体   繁体   English

pthread_cond_timedwait立即返回ETIMEDOUT

[英]pthread_cond_timedwait returns ETIMEDOUT immediately

I am trying to use pthread_cond_timedwait to wait with a timeout similar to Java's wait(long timeout, int nanos) . 我正在尝试使用pthread_cond_timedwait来等待类似于Java的wait(long timeout, int nanos) I understand that Java's wait uses a relative timeout, whereas pthread_cond_timedwait uses an absolute time threshold. 我知道Java的wait使用相对超时,而pthread_cond_timedwait使用绝对时间阈值。 Despite taking this into account, pthread_cond_timedwait appears to return immediately with the error code ETIMEDOUT. 尽管考虑到这一点, pthread_cond_timedwait似乎立即返回,并显示错误代码ETIMEDOUT。

The sample program below prints a value <0. 下面的示例程序打印一个值<0。 I would expect it to print a value >=0. 我希望它可以打印> = 0的值。

Am I using pthread_cond_timedwait incorrectly? 我使用pthread_cond_timedwait不正确吗? How would I rewrite the below program to add a delay of eg 5 seconds? 我如何重写下面的程序以增加例如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;
}

You are using the wrong clock. 您使用了错误的时钟。 The default clock used by pthread_cond_timedwait is CLOCK_REALTIME . pthread_cond_timedwait使用的默认时钟为CLOCK_REALTIME If you really want to use CLOCK_MONOTONIC instead, you'll need to set the clock attribute of your condition variable: 如果您确实想使用CLOCK_MONOTONIC ,则需要设置条件变量的clock属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM