【发布时间】:2020-03-25 12:32:45
【问题描述】:
所以我试图了解 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));
}
【问题讨论】:
-
您好,欢迎来到 SO!第一:
timespec的其他成员不应该被初始化吗?我不知道如果tv_nsec包含超出范围的内容会发生什么。第二:您预计会发生什么,正在发生什么? -
对
pthread_cond_timedwait()的调用的返回值传达了有关所发生事件的有用且相关的信息,但所显示的程序忽略了它。
标签: c multithreading pthreads mutex thread-synchronization