I am unable to find a function to convert a thread id (pid_t
) into a pthread_t
which would allow me to call pthread_cancel()
or pthread_kill()
.
Even if pthreads doesn’t provide one is there a Linux specific function? I don’t think such a function exists but I would be happy to be corrected.
Background
I am well aware that it is usually preferable to have threads manage their own lifetimes via condition variables and the like.
This use is for testing purposes. I am trying to find a way to test how an application behaves when one of its threads ‘dies’. So I’m really looking for a way to kill a thread. Using syscall(tgkill())
kills the process, so instead I provided a means for a tester to give the process the id of the thread to kill. I now need to turn that id into a pthread_t so that I can then:
- use
pthread_kill(tid,0)
to check for its existence followed by - calling
pthread_kill()
orpthread_cancel()
as appropriate.
This is probably taking testing to an unnecessary extreme. If I really want to do that some kind of mock pthreads implementation might be better.
Indeed if you really want robust isolation you are typically better off using processes rather than threads.
Advertisement
Answer
I don’t think such a function exists but I would be happy to be corrected.
As a workaround I can create a table mapping &pthread_t
to pid_t
and ensure that I always invoke pthread_create()
via a wrapper that adds an entry to this table. This works very well and allows me to convert an OS thread id to a pthread_t
which I can then terminate using pthread_cancel()
. Here is a snippet of the mechanism:
typedef void* (*threadFunc)(void*); static void* start_thread(void* arg) { threadFunc threadRoutine = routine_to_start; record_thread_start(pthread_self(),syscall(SYS_gettid)); routine_to_start = NULL; //let creating thread know its safe to continue return threadRoutine(arg); }