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

7

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

3个回答

7

创建一个线程子类,在初始化时设置parent属性:

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对象。


哦,我喜欢。这个想法有一些自检的可能性。你可能想把mythread.parent作为一个属性,如果父线程“not is_alive()”则返回False。或者创建一个MainThreadChild类,它具有一个类属性“parent”,而不是实例属性“parent”,以便该类型的所有线程基本上都期望绑定到某个线程。 - DevPlayer

1
你可以在子线程中引用父线程,并获取其ID。

0

在创建子线程时,您可能希望将MainThread的名称传递给子线程。

另一个选择是,如果您正在使用类,则可以使子线程的目标指向MainThread类中的方法:

class MainThread:
    name = "MainThreadName"

    def child_thread_run(self):
        print self.name # Will print "MainThreadName", even from a child thread

    def run(self):
        child = threading.Thread(target=self.child_thread_run)
        child.start()

这是一种非常糟糕的方法。 - DUDE_MXP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接