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?
CodePudding user response:
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...