fgsfdsfgts
fgsfdsfgts

Reputation: 87

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). I understand that Java's wait uses a relative timeout, whereas pthread_cond_timedwait uses an absolute time threshold. Despite taking this into account, pthread_cond_timedwait appears to return immediately with the error code ETIMEDOUT.

The sample program below prints a value <0. I would expect it to print a value >=0.

Am I using pthread_cond_timedwait incorrectly? How would I rewrite the below program to add a delay of e.g. 5 seconds?

#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;
}

Upvotes: 4

Views: 4362

Answers (1)

Miles Budnek
Miles Budnek

Reputation: 30494

You are using the wrong clock. The default clock used by pthread_cond_timedwait is CLOCK_REALTIME. If you really want to use CLOCK_MONOTONIC instead, you'll need to set the clock attribute of your condition variable:

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

Upvotes: 14

Related Questions