8

我花了最后一个小时(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 个实例......直到现在我找不到这个问题的(工作)解决方案......实际的类是一个计时器,该方法是一个更新所有计数器变量的更新方法。由于此类还必须在给定时间运行函数,因此时间更新不会被主线程阻塞是很重要的。

任何帮助深表感谢。提前谢谢...

4

2 回答 2

18

在这种特定情况下,您可以直接从 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()
于 2013-08-24T07:50:54.023 回答
2

为了在线程中运行一个函数(或成员函数),使用这个:

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

与 deriving from 相比Thread,它的优点是您不会将 Thread 的所有公共函数导出为自己的公共函数。实际上,您甚至不需要编写一个类来使用此代码,self.function或者global_function两者都可以像target这里一样使用。

我还考虑使用上下文管理器来启动/停止线程,否则线程可能会比必要的存活时间更长,导致资源泄漏和关闭时出错。由于您要将其放入一个类中,因此请在 in 中启动线程__enter__并加入它__exit__

于 2013-08-24T13:02:24.517 回答