Windows下pthread_cond_timedwait()返回错误码10060问题求助
解决Windows下pthread_cond_timedwait返回10060错误的问题
你遇到的错误码10060对应Windows的WSAETIMEDOUT,根源是Windows和Linux下的pthread库对pthread_cond_timedwait的超时参数要求完全不同:
- 在Linux上,
timespec传入的是相对超时时间(从调用函数开始,等待指定的时长); - 但在Windows上的大多数pthread实现(比如MinGW的pthreads-w32库),要求传入绝对超时时间(当前系统时间加上等待时长后的具体时间点)。
你现在直接传timeout.tv_sec = 1,会被库当成一个早已过去的绝对时间,所以立刻返回超时错误。
修复方案:计算绝对超时时间
你需要先获取当前系统时间,再叠加你想要等待的时长,生成绝对时间后传入函数。修改后的代码如下:
#include <fstream> #include <Windows.h> #define HAVE_STRUCT_TIMESPEC #include <pthread.h> #include <time.h> // 必须包含time.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); // 计算绝对超时时间:当前时间 + 等待1秒 struct timespec now; clock_gettime(CLOCK_REALTIME, &now); // 获取当前系统实时时间 const int wait_seconds = 1; const long wait_nanoseconds = 0; timeout.tv_sec = now.tv_sec + wait_seconds; timeout.tv_nsec = now.tv_nsec + wait_nanoseconds; // 处理纳秒溢出的情况(如果相加后超过1e9纳秒,进位到秒) if (timeout.tv_nsec >= 1000000000) { timeout.tv_sec += 1; timeout.tv_nsec -= 1000000000; } 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()); // 注意:tv_sec是time_t类型,用%lld避免溢出 printf("tv_sec = %lld tv_nsec = %ld\n", (long long)timeout.tv_sec, timeout.tv_nsec); pthread_mutex_unlock(&mutex); pthread_cond_destroy(&condVar); pthread_mutex_destroy(&mutex); return 0; }
额外注意事项
- 编译时要确保链接pthread库,比如MinGW下编译命令要加
-lpthread参数; - 如果你使用的是其他Windows pthread实现,建议先查阅官方文档确认超时参数的类型(绝对/相对);
- 错误码10060是Windows系统级的超时错误,你的pthread库直接映射了这个错误,而不是POSIX标准的
ETIMEDOUT(错误码110),这也是Windows平台pthread实现的一个常见特性。
内容的提问来源于stack exchange,提问作者Vlad
相关产品推荐
相关产品推荐

