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

8

我花了最近的一个小时(或几个小时)在寻找/谷歌上搜索一种方法,让一个类在实例化时立即启动其中一个方法以在新线程中运行。

我可以运行类似以下代码:

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个该类的实例... 直到现在我都没有找到(可行的)解决方法... 实际的类是一个计时器,该方法是一个更新方法,用于更新所有计数器变量。由于该类还必须在特定时间运行函数,因此重要的是时间更新不会被主线程阻塞。
非常感谢您的帮助。提前致谢...

1
当您尝试将该代码放入MyClas.__init__中时,遇到了什么问题? - user4815162342
2个回答

22

在这种特定情况下,您可以直接从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分。你可能应该至少包括更新方法的签名,因为你的答案看起来像是一个完整的可工作代码片段。此外,它缺少了sleep的导入语句。 - Henrik
这个运行得非常好...有时候解决方案非常简单。我有类似的想法,但是我无法让它运行起来。非常感谢...有时候我只是看不到树木中的森林。 - hegoe

2
为了在线程中运行一个函数(或成员函数),请使用以下代码:
th = Thread(target=some_func)
th.daemon = True
th.start()

与从Thread派生不同的是,它有一个优点,即您不需要将所有的Thread公共函数导出为自己的公共函数。实际上,您甚至不需要编写一个类来使用这个代码,self.functionglobal_function都可以像target一样使用。
我还会考虑使用上下文管理器来启动/停止线程,否则线程可能会比必要的时间更长地保持活动状态,导致资源泄漏和关闭时出现错误。由于您正在将此放入一个类中,在__enter__中启动线程,并在__exit__中与其加入。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接