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?
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)
Then, while doing work inside a thread started with this class, we can access
current_thread().parent to get the spawning Thread object.
You can have a reference to parent thread on child thread.. and then get it's ID
You might want to pass the name of MainThread to the child threads on creation.
Another option, if you're working with a class, is to have the target of the child threads point to a method from the class of 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()