Python类实例在新线程中启动方法

时间:2013-08-24 07:22:57

标签: python multithreading class

我花了最后一小时(s ???)查找/谷歌搜索方法让一个类在一个新的线程中启动其中一个方法,一旦它被实例化。

我可以运行这样的东西:

x = myClass()

def updater():
    while True:
        x.update()
        sleep(0.01)

update_thread = Thread(target=updater) 
update_thread.daemon = True
update_thread.start()

更优雅的方法是让课程在实例化时在 init 中完成。 想象一下,该课程有10个实例...... 到目前为止,我找不到这个问题的(工作)解决方案...... 实际的类是一个计时器,该方法是一个更新所有计数器变量的更新方法。由于此类还必须在给定时间运行函数,因此主线程不会阻止时间更新。

非常感谢任何帮助。 Thx提前......

2 个答案:

答案 0 :(得分:15)

在这种特定情况下,您可以直接从Thread子类化

from threading import Thread

class MyClass(Thread):
    def __init__(self, other, arguments, here):
        super(MyClass, self).__init__()
        self.daemon = True
        self.cancelled = False
        # do other initialization here

    def run(self):
        """Overloaded Thread.run, runs the update 
        method once per every 10 milliseconds."""

        while not self.cancelled:
            self.update()
            sleep(0.01)

    def cancel(self):
        """End this timer thread"""
        self.cancelled = True

    def update(self):
        """Update the counters"""
        pass

my_class_instance = MyClass()

# explicit start is better than implicit start in constructor
my_class_instance.start()

# you can kill the thread with
my_class_instance.cancel()

答案 1 :(得分:2)

要在线程中运行函数(或成员函数),请使用:

th = Thread(target=some_func)
th.daemon = True
th.start()

将此与从Thread派生的比较,它的优点是您不会将所有Thread的公共函数导出为自己的公共函数。实际上,您甚至不需要编写类来使用此代码,self.functionglobal_function在此处同样可用作target

我还考虑使用上下文管理器来启动/停止线程,否则线程可能会保持活动时间超过必要时间,导致资源泄漏和关闭时出错。由于您要将其放入类中,请在__enter__中启动该主题并在__exit__中加入该主题。

相关问题