如何在Python中传递和运行回调方法 [英] How to pass and run a callback method in Python

查看:211
本文介绍了如何在Python中传递和运行回调方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个管理器(主线程),该管理器创建了其他线程来处理各种操作. 我希望在其创建的线程结束时(当run()方法执行完成时)通知我的Manager.

I have a Manager (main thread), that creates other Threads to handle various operations. I would like my Manager to be notified when a Thread it created ends (when run() method execution is finished).

我知道我可以通过使用Thread.isActive()方法检查所有线程的状态来做到这一点,但是轮询很糟糕,所以我想收到通知.

I know I could do it by checking the status of all my threads with the Thread.isActive() method, but polling sucks, so I wanted to have notifications.

我正在考虑为线程提供一个回调方法,并在run()方法的末尾调用此函数:

I was thinking of giving a callback method to the Threads, and call this function at the end of the run() method:

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?
    ...

谢谢!

推荐答案

除非具有对管理器的引用,否则该线程无法调用管理器.最简单的方法是管理器在实例化时将其提供给线程.

The thread can't call the manager unless it has a reference to the manager. The easiest way for that to happen is for the manager to give it to the thread at instantiation.

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()

如果您希望能够将任意函数或方法分配为回调,而不是存储对管理器对象的引用,则由于方法包装程序等原因,这会带来一些问题.设计回调很困难,因此它需要对管理器的引用,而这正是您想要的.我做了一段时间,没有提出我认为有用或优雅的内容.

If you want to be able to assign an arbitrary function or method as a callback, rather than storing a reference to the manager object, this becomes a bit problematic because of method wrappers and such. It's hard to design the callback so it gets a reference to both the manager and the thread, which is what you will want. I worked on that for a while and did not come up with anything I'd consider useful or elegant.

这篇关于如何在Python中传递和运行回调方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆