我无法找到将线程ID(pid_t
)转换为pthread_t
的函数,这样我就可以调用pthread_cancel()
或pthread_kill()
。
即使pthreads没有提供一个是否有Linux特定的功能? 我不认为这样的功能存在,但我很乐意纠正。
我很清楚通常情况下让线程通过条件变量等来管理自己的生命周期。
此用途用于测试目的。我试图找到一种方法来测试应用程序在其中一个线程“死亡”时的行为方式。所以我真的在寻找一种杀死线程的方法。使用syscall(tgkill())
会终止进程,因此我为测试人员提供了一种方法,让进程获得要杀死的线程的id。我现在需要将该id转换为pthread_t,以便我可以:
pthread_kill(tid,0)
检查其存在,然后pthread_kill()
或pthread_cancel()
。这可能会将测试带到一个不必要的极端。如果我真的想这样做,某种模拟pthread实现可能会更好。
事实上,如果你真的想要强大的隔离,你通常最好使用进程而不是线程。
答案 0 :(得分:1)
我认为这种功能不存在,但我很乐意予以纠正。
作为一种解决方法,我可以创建一个映射&pthread_t
到pid_t
的表,并确保始终通过向该表添加条目的包装器调用pthread_create()
。这非常有效,并允许我将操作系统线程ID转换为pthread_t
,然后我可以使用pthread_cancel()
终止。以下是该机制的片段:
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);
}