我正在寻找从子线程获取父ID或名称的方式。 在例子中,我有主线程为MainThread。在这个线程中,我创建了一些新线程。然后我使用threading.enumerate()
来获得对所有正在运行的线程的引用,选择一个子线程并以某种方式获取MainThread的ID或名称。有什么办法做到这一点?Python线程 - 如何获取父ID /名称
4
A
回答
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对象。
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()
相关问题
- 1. 如何获取所有线程ID和进程的名称
- 2. 如何从父级获取线程名称?
- 3. 如何从其名称/ ID获取线程的实例?
- 4. 如何获取Win32线程的名称?
- 5. 如何通过知道线程ID来获取线程的名称?
- 6. 如何获取父方法名称?
- 7. 从进程名称获取进程ID
- 8. 获取父页面名称
- 9. 如何获取Node的id名称?
- 10. 如何按名称获取id顶点?
- 11. 如何在Python中获取父目录的名称?
- 12. C++如何获取父进程ID
- 13. 线程ID从线程名称
- 14. 获取父类名称?
- 15. 如何在php mysql中获取父名称和名称?
- 16. 通过名称获取进程ID
- 17. 如何从进程名称获取进程ID?
- 18. 我如何知道线程ID为PDH的线程名称
- 19. Tinythread ++:获取线程ID
- 20. 获取线程ID
- 21. 如何从子线程或其他线程获取父线程?
- 22. 如何获得Hogging线程名称WLST
- 23. 如何在.NET中获取父项目的程序集名称?
- 24. 如何获取窗口名称? [Python]
- 25. 从ThreadID获取线程名称
- 26. 如何获得密钥名称id Id
- 27. 如何从RWThreadId获取Linux线程ID?
- 28. 如何获取Android线程ID?
- 29. 如何使用模块获取进程ID,名称和状态
- 30. 我如何从进程ID获取服务的名称?
哦,我喜欢。这个想法有一些自我检查的可能性。如果父类“不是is_alive()”,您可能希望使mythread.parent属性返回False。或者使用类属性“parent”而不是实例属性“parent”来创建MainThreadChild类,以便此类型的所有线程基本上都期望被绑定到某个特定的线程。 – DevPlayer