2011-07-01 38 views
4

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

回答

3

让一个线程子类,设置一个parent属性上的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对象。

+0

哦,我喜欢。这个想法有一些自我检查的可能性。如果父类“不是is_alive()”,您可能希望使mythread.parent属性返回False。或者使用类属性“parent”而不是实例属性“parent”来创建MainThreadChild类,以便此类型的所有线程基本上都期望被绑定到某个特定的线程。 – DevPlayer

1

您可以到子线程父线程参考..然后得到它的ID

1

您可能要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()