我找不到将线程 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()
。
这可能将测试带到了不必要的极端。如果我真的想这样做,某种模拟 pthreads 实现可能会更好。
事实上,如果您真的想要强大的隔离,通常最好使用进程而不是线程。
最佳答案
我认为不存在这样的功能,但我很乐意得到纠正。
作为一种变通方法,我可以创建一个将 &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);
}
关于linux - 从线程 ID 获取 pthread_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46323502/