heg*_*goe 8 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()
Run Code Online (Sandbox Code Playgroud)
更优雅的方法是让类在init实现时在init中执行.想象一下,该类有10个实例......到目前为止,我找不到这个问题的(工作)解决方案......实际的类是一个计时器,该方法是一个更新所有计数器变量的更新方法.由于此类还必须在给定时间运行函数,因此主线程不会阻止时间更新.
任何帮助深表感谢.先谢谢......
Ant*_*ala 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()
Run Code Online (Sandbox Code Playgroud)