我正在尝试将检测添加到我的代码中,它将打印出类似
I am trying to add instrumentation into my code that will print out something like
'线程 1 分叉线程 2'
'Thread 1 forks Thread 2'
关于如何实现这一目标有什么建议吗?
Any suggestions on how I can achieve this?
推荐答案术语更正:一个线程可以创建另一个线程,而不是 fork,这通常是用于提及一个进程分叉另一个进程.
Terminology correction: one thread may create another thread, not fork, which is usually used to mention one process forking another.
不,一个线程无法获得另一个线程的标识符.在 Linux 上,您可以检查 gettid() == getpid() 是否是主线程.Solaris 有 thr_main() 来识别调用者是否是主线程.FreeBSD 有 pthread_main_np() 出于同样的目的.
No, a thread has no way to get another thread's identifier. On Linux, you can check if gettid() == getpid() to find if it's the main thread. Solaris has thr_main() to identify if the caller is main thread or not. FreeBSD has pthread_main_np() for the same purpose.
但是没有办法识别任何线程之间的父子关系.任何线程都可以创建更多线程.您必须在创建线程时使用传递线程标识符或使用全局数据结构来维护此信息.
But there's no way to identify parent-child relationship between any threads. Any thread can create more threads. You'll have to use pass the thread identifiers around when creating threads or use global data structure to maintain this information.
更多推荐
是否可以从孩子那里获取父线程 ID?
发布评论