所以我试图了解pthread_cond_timedwait()的工作方式,因为在项目同步方面遇到一些问题。这是我想出的代码,但是没有按我认为的那样工作。我的目标是打印时间,等待2秒钟,然后再次打印时间以查看时间的流逝。
//gcc -Wall -pthread timedwait.c -o exe
#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));
}