【问题标题】:pthread_cond_timedwait() in WindowsWindows 中的 pthread_cond_timedwait()
【发布时间】: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 线程。
  • 除此之外:当您打印 errnoGetLastError() 值时,它们可能已经通过调用 printf() 进行了修改。
  • 不清楚为什么它会在 windows 上返回超时,你的代码是错误的。 pthread_cond_timedwait 期望绝对时间,而不是延迟。修复后,两个平台都会出现超时错误。
  • 您能否举例说明如何在 Windows 中填充 struct timespec 超时。

标签: c++ windows pthreads


【解决方案1】:

pthread_cond_timedwait() 返回 10060,它看起来像 WSAETIMEDOUT 的值。我很惊讶该函数没有按预期返回 ETIMEDOUT。

无论如何,这是一个超时,这不足为奇,因为在您的示例中没有其他线程向条件变量发出信号。

【讨论】:

  • 函数不返回 ETIMEDOUT 它确实。在 Windows E... 错误代码是根据相应的 WSAE... 代码定义的。
猜你喜欢
  • 2010-12-01
  • 2012-12-24
  • 2014-02-13
  • 1970-01-01
  • 2010-10-14
  • 2013-04-07
  • 2020-03-25
  • 2018-02-11
  • 2012-07-30
相关资源
最近更新 更多