我花了最后一个小时(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 个该类的实例...... 直到现在我都找不到解决这个问题的(有效的)解决方案...... 实际的类是一个计时器,方法是更新所有计数器变量的更新方法。由于此类还必须在给定时间运行函数,所以时间更新不会被主线程阻塞是很重要的。
非常感谢任何帮助。提前致谢...
最佳答案
在这种特定情况下,您可以直接从 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()
关于Python类实例在新线程中启动方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18416116/