1
votes

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() or pthread_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.

1
I don't think you can. Anyway this may help you out unix.stackexchange.com/questions/1066/… - rakwaht
pthread_kill doesn't kill a thread, it sends a signal (and it can bring down the entire process). Anyway, why on earth do you even deal with kernel thread ids? They are not even exposed by glibc. - n. 1.8e9-where's-my-share m.
A pthread_t is opaque so there is no way I can specify a specific thread to terminate. However, ps or top -H can show the thread ids from the command line. You can set the signal mask so that signals only go to specific threads. In this case pthread_kill() might be handled safely. - Bruce Adams

1 Answers

2
votes

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);
}