1
The purpose of this function is to show the hours, wait for 2 seconds, and show the hours again to make sure that 2 seconds have passed. I am not using sleeps as this function is to help me understand how the pthread_cond_timedwait function works so I can use it as a synchronization method.
//gcc -Wall -pthread timedwait.c -o timedwait
#define _OPEN_THREADS
#include <pthread.h>
#include <stdio.h>
#include <time.h>
#include <errno.h>
#include <stdlib.h>
int main() {
pthread_cond_t cond;
pthread_mutex_t mutex;
time_t T;
struct timespec t;
if (pthread_cond_init(&cond, NULL) != 0) {
perror("pthread_cond_init() error");
exit(2);
}
time(&T);
t.tv_sec = T + 2;
printf("starting timedwait at %s", ctime(&T));
pthread_cond_timedwait(&cond, &mutex, &t);
time(&T);
printf("timedwait over at %s", ctime(&T));
}
I tested now giving lock and Unlock to mutex and did not work, ran the second print, without expecting any second.
– João Marcelino
I tested my code on macos, does Linux need to pick up the time with clock_gettime() instead of time()? Another time I’ll test this, it would be an interesting difference to document.
– epx
I put here the resolution that works with the help in the English stackoverflow, and the clock_gettime was used, maybe it was that.
– João Marcelino
I tested on Linux now and neither my version nor yours were working. What you solved, for both of them, was to compile with -lpthread. I think in macos pthread is implicit, but not in Linux, and Linux plays the behavior of never waiting for condition when it is compiled without pthread (assumes it is single-threaded).
– epx