【发布时间】:2018-05-29 13:52:25
【问题描述】:
我尝试在我的代码中实现pthread 功能。不幸的是,我无法正确实现函数pthread_cond_timedwait()。
在 Linux 中一切正常。但在 Windows 中,此函数总是返回错误代码 10060。这是我的简单代码:
#include <fstream>
#include <Windows.h>
#define HAVE_STRUCT_TIMESPEC
#include <pthread.h>
int main()
{
int rcTimedwait = 0;
struct timespec timeout;
pthread_mutex_t mutex;
pthread_cond_t condVar;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&condVar, NULL);
timeout.tv_sec = 1;
timeout.tv_nsec = 0;
SetLastError(0);
errno = 0;
pthread_mutex_lock(&mutex);
rcTimedwait = pthread_cond_timedwait(&condVar, &mutex, &timeout);
printf("rcTimedwait = %d\n", rcTimedwait);
printf("errno = %d GetLastError = %d\n", errno, GetLastError());
printf("tv_sec = %d tv_nsec = %d\n", timeout.tv_sec, timeout.tv_nsec);
pthread_mutex_unlock(&mutex);
pthread_cond_destroy(&condVar);
pthread_mutex_destroy(&mutex);
return 0;
}
和输出:
rcTimedwait = 10060
errno = 0 GetLastError = 0
tv_sec = 1 tv_nsec = 0
提前感谢您的帮助,对我的英语感到抱歉
【问题讨论】:
-
使用 C++11 线程。
-
除此之外:当您打印
errno或GetLastError()值时,它们可能已经通过调用printf()进行了修改。 -
不清楚为什么它会在 windows 上返回超时,你的代码是错误的。
pthread_cond_timedwait期望绝对时间,而不是延迟。修复后,两个平台都会出现超时错误。 -
您能否举例说明如何在 Windows 中填充 struct timespec 超时。