2013-08-24 19 views
7

我花了最后一个小时(s ???)寻找/搜索方法,让一个类在新线程中立即启动它的一个方法。Python类实例在新线程中启动方法

我可以像这样运行的东西:

x = myClass() 

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

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

更优雅的方式将有类做它初始化当它被实例化。 想象一下,有10个该类的实例... 直到现在我找不到这个问题的(工作)解决方案... 实际的类是一个计时器和方法是更新所有计数器的变量。由于这个类还必须在给定的时间运行函数,所以时间更新不会被主线程阻塞是很重要的。

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

+1

当您试图将该代码放入'MyClas .__ init__'时遇到什么问题? – user4815162342

回答

14

可以在这种特殊情况下

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

打我半分钟。 +1为好的答案。您应该至少包含更新方法的签名,因为您的答案看起来应该是一个完整的代码片段。此外,它没有输入“睡眠”声明。 – Henrik

+0

这就像一个魅力......有时候解决方案非常简单。我有一个类似的方法,但我无法得到它运行。非常感谢...有时我只是看不到树木。 – hegoe

2

为了运行在一个线程函数(或memberfunction)从主题直接继承,使用此:

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

将其与Thread派生出来,它的优点是不会将所有的Thread公共函数导出为自己的公共函数。其实,你甚至不需要编写一个类来使用这个代码,self.functionglobal_function在这里都可以同样用作target

我还考虑使用上下文管理器来启动/停止线程,否则线程可能会保持活动时间超过必要的时间,导致资源泄漏和关闭时的错误。既然你把这个放到一个班级里,那么从__enter__开始线程并加入__exit__