multithreading - Python class instance starts method in new thread -
i spent last hour(s???) looking/googling way have class start 1 of methods in new thread instanciated.
i run this:
x = myclass() def updater(): while true: x.update() sleep(0.01) update_thread = thread(target=updater) update_thread.daemon = true update_thread.start()
a more elegant way have class doing in init when instanciated. imagine having 10 instances of class... until couldn't find (working) solution problem... actual class timer , method update method updates counter's variables. class has run functions @ given time important time updates won't blocked main thread.
any appreciated. thx in advance...
you can subclass directly thread in specific case
from threading import thread class myclass(thread): def __init__(self, other, arguments, here): super(myclass, self).__init__() self.daemon = true self.cancelled = false # other initialization here def run(self): """overloaded thread.run, runs update method once per every 10 milliseconds.""" while not self.cancelled: self.update() sleep(0.01) def cancel(self): """end timer thread""" self.cancelled = true def update(self): """update counters""" pass my_class_instance = myclass() # explicit start better implicit start in constructor my_class_instance.start() # can kill thread my_class_instance.cancel()
Comments
Post a Comment