是否可以从孩子那里获取父线程 ID? [英] Is it possible to get parent threadID from child?

查看:79
本文介绍了是否可以从孩子那里获取父线程 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将检测添加到我的代码中,它将打印出类似

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆