Python线程 - 如何获取父ID /名称

Gal*_*lmi 6 python multithreading

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

ete*_*ode 5

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

from threading import current_thread

class MyThread(threading.Thread):
    def __init__(self, *args, **kwargs):
        self.parent = current_thread()
        Thread.__init__(self, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

然后,在从这个类开始的线程内部工作时,我们可以访问current_thread().parent以获取产生Thread对象.