线程 - 如何获取父 ID/名称? [英] threading - how to get parent id/name?

查看:51
本文介绍了线程 - 如何获取父 ID/名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找从子线程获取父 ID 或名称的方法.例如,我将主线程作为 MainThread.在这个线程中,我创建了几个新线程.然后我使用 threading.enumerate() 获取对所有正在运行的线程的引用,选择一个子线程并以某种方式获取 MainThread 的 ID 或名称.有什么办法吗?

I looking for the way to get parent ID or name from child thread. In example, I have main thread as MainThread. In this thread i create a few new threads. Then I use threading.enumerate() to get references to all running thread, pick one of child threads and somehow get ID or name of MainThread. Is any way to do that?

推荐答案

创建一个 Thread 子类,在 init 上设置 parent 属性:

Make a Thread subclass that sets a parent attribute on init:

from threading import current_thread

class MyThread(threading.Thread):
    def __init__(self, *args, **kwargs):
        self.parent = current_thread()
        Thread.__init__(self, *args, **kwargs)

然后,在以此类启动的线程内部工作时,我们可以访问 current_thread().parent 以获取生成的 Thread 对象.

Then, while doing work inside a thread started with this class, we can access current_thread().parent to get the spawning Thread object.

这篇关于线程 - 如何获取父 ID/名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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