本文介绍了Python线程-如何获取父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.

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

08-20 06:08