为什么在winpthreads的'纳米leep”实现中多次调用`pthread_testcancel`?

发布于 2025-02-12 19:54:50 字数 1239 浏览 0 评论 0原文

nanosleep winpthreads的实现,它是Windows的POSIX线程的端口,在其实现中多次调用pthread_testcancel

nanosleep in [ nanosleep.c ]调用pthread_delay_np_ms未导出并进行实际睡眠。这是pthread_delay_np_ms in [ thread.c ]。

int
pthread_delay_np_ms (DWORD to)
{
  struct _pthread_v *s = __pthread_self_lite ();

  if (!to)
    {
      pthread_testcancel ();
      Sleep (0);
      pthread_testcancel ();
      return 0;
    }
  pthread_testcancel ();
  if (s->evStart)
    WaitForSingleObject (s->evStart, to);
  else
    Sleep (to);
  pthread_testcancel ();
  return 0;
}

您可以看到PTHREAD_TESTCANCEL由于某种原因被称为多次。

我认为这可能与以下内容一样简单的额外代码的原因是什么?

int
pthread_delay_np_ms (DWORD to)
{
  Sleep (to);
  return 0;
}

pthread_testcancel实现什么?另外,一个问题是为什么waitforsingleobject优先于睡眠当可用时可用?

The nanosleep implementation of winpthreads, which is a port of POSIX threads to Windows, calls pthread_testcancel multiple times in its implementation.

nanosleep in [nanosleep.c] calls pthread_delay_np_ms which is not exported and does the actual sleeping. This is the code of pthread_delay_np_ms in [thread.c].

int
pthread_delay_np_ms (DWORD to)
{
  struct _pthread_v *s = __pthread_self_lite ();

  if (!to)
    {
      pthread_testcancel ();
      Sleep (0);
      pthread_testcancel ();
      return 0;
    }
  pthread_testcancel ();
  if (s->evStart)
    WaitForSingleObject (s->evStart, to);
  else
    Sleep (to);
  pthread_testcancel ();
  return 0;
}

You can see pthread_testcancel is called multiple times for some reason.

What is the reason for the additional code while I think this could be as simple as follows?

int
pthread_delay_np_ms (DWORD to)
{
  Sleep (to);
  return 0;
}

What does pthread_testcancel achieve? Also, a side question is why is WaitForSingleObject preferred over Sleep when a dummy event handle is available?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我一向站在原地 2025-02-19 19:54:50

另一个线程可以调用pthread_cancel在这种情况下waitforsingleobject将立即返回,并且在您的简单睡眠时将杀死该线程在未知的时间内。

为什么他们在睡觉(0)之前调用pthread_testcancel,如果(s-> evstart),我不知道。也许您应该直接询问作者是否在乎。我认为他们在那里是有原因的...

Another thread can call pthread_cancel in which case WaitForSingleObject will return immediately and the thread will be killed while your simple Sleep would keep a now pointless thread around for an unknown amount of time.

Why they are calling pthread_testcancel before Sleep(0) and if (s->evStart), I don't know. Maybe you should ask the authors directly if you care that much about it. I assume they are there for a reason...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文