Python class instance starts method in new thread Python class instance starts method in new thread multithreading multithreading

Python class instance starts method in new thread


You can subclass directly from Thread in this specific case

from threading import Threadclass 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"""        passmy_class_instance = MyClass()# explicit start is better than implicit start in constructormy_class_instance.start()# you can kill the thread withmy_class_instance.cancel()


In order to run a function (or memberfunction) in a thread, use this:

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

Comparing this with deriving from Thread, it has the advantage that you don't export all of Thread's public functions as own public functions. Actually, you don't even need to write a class to use this code, self.function or global_function are both equally usable as target here.

I'd also consider using a context manager to start/stop the thread, otherwise the thread might stay alive longer than necessary, leading to resource leaks and errors on shutdown. Since you're putting this into a class, start the thread in __enter__ and join with it in __exit__.