I'd like to determine if a particular thread 'exists'.
pthread_kill() appears to be suited to this task, at least according to its man page.
If sig is 0, then no signal is sent, but error checking is still performed.
Or, as my system's man page puts it:
If sig is 0, then no signal is sent, but error checking is still performed; this can be used to check for the existence of a thread ID.
However when I attempt to pass in an uninitialized pthread_t, the application invariably SEGFAULTs.
Digging into this, the following snippet from pthread_kill.c (from my toolchain) appears to do no error checking, and simply attempts to de-reference threadid (the de-reference is at pd->tid).
int
__pthread_kill (threadid, signo)
pthread_t threadid;
int signo;
{
struct pthread *pd = (struct pthread *) threadid;
/* Make sure the descriptor is valid. */
if (DEBUGGING_P && INVALID_TD_P (pd))
/* Not a valid thread handle. */
return ESRCH;
/* Force load of pd->tid into local variable or register. Otherwise
if a thread exits between ESRCH test and tgkill, we might return
EINVAL, because pd->tid would be cleared by the kernel. */
pid_t tid = atomic_forced_read (pd->tid);
if (__builtin_expect (tid <= 0, 0))
/* Not a valid thread handle. */
return ESRCH;
We can't even rely on zero being a good initializer, because of the following:
# define DEBUGGING_P 0
/* Simplified test. This will not catch all invalid descriptors but
is better than nothing. And if the test triggers the thread
descriptor is guaranteed to be invalid. */
# define INVALID_TD_P(pd) __builtin_expect ((pd)->tid <= 0, 0)
Additionally, I noticed the following in the linked man page (but not on my system's):
POSIX.1-2008 recommends that if an implementation detects the use of a thread ID after the end of its lifetime, pthread_kill() should return the error ESRCH. The glibc implementation returns this error in the cases where an invalid thread ID can be detected. But note also that POSIX says that an attempt to use a thread ID whose lifetime has ended produces undefined behavior, and an attempt to use an invalid thread ID in a call to pthread_kill() can, for example, cause a segmentation fault.
As outlined here by R.., I'm asking for the dreaded undefined behavior.
It would appear that the manual is indeed misleading - particularly so on my system.
- Is there a good / reliable way to ask find out if a thread exists? (presumably by not using
pthread_kill()) - Is there a good value that can be used to initialize
pthread_ttype variables, even if we have to catch them ourselves?
I'm suspecting that the answer is to employ pthread_cleanup_push() and keep an is_running flag of my own, but would like to hear thoughts from others.