如何在Python中传递和运行回调方法
我有一个管理器(主线程),它创建其他线程来处理各种操作。我希望在其创建的线程结束时(当run()方法执行完成时)通知我的Manager。
我知道我可以通过使用Thread.isActive()方法检查我所有线程的状态来做到这一点,但是轮询很糟糕,所以我想收到通知。
我正在考虑给线程提供一个回调方法,并在run()方法的末尾调用此函数:
class Manager():
...
MyThread(self.on_thread_finished).start() # How do I pass the callback
def on_thread_finished(self, data):
pass
...
class MyThread(Thread):
...
def run(self):
....
self.callback(data) # How do I call the callback?
...
谢谢!
-
除非具有对管理器的引用,否则该线程无法调用管理器。最简单的方法是管理器在实例化时将其提供给线程。
class Manager(object): def new_thread(self): return MyThread(parent=self) def on_thread_finished(self, thread, data): print thread, data class MyThread(Thread): def __init__(self, parent=None): self.parent = parent super(MyThread, self).__init__() def run(self): # ... self.parent and self.parent.on_thread_finished(self, 42) mgr = Manager() thread = mgr.new_thread() thread.start()
如果您希望能够将任意函数或方法分配为回调,而不是存储对管理器对象的引用,则由于方法包装器等原因,这将带来一些问题。设计回调很困难,因此它需要引用管理器
和 线程。我做了一段时间,没有提出任何我认为有用或优雅的东西。