Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python class instance starts method in new thread

I spent the last hour(s???) looking/googling for a way to have a class start one of its methods in a new thread as soon as it is instanciated.

I could run something like 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 would be to have the class doing it in init when it is instanciated. Imagine having 10 instances of that class... Until now I couldn't find a (working) solution for this problem... The actual class is a timer and the method is an update method that updates all the counter's variables. As this class also has to run functions at a given time it is important that the time updates won't be blocked by the main thread.

Any help is much appreciated. Thx in advance...

like image 386
hegoe Avatar asked Aug 24 '13 07:08

hegoe


People also ask

Which method is executed when the start () method of a thread object is called Python?

New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed.

How do you start a thread class in Python?

Use the Python threading module to create a multi-threaded application. Use the Thread(function, args) to create a new thread. Call the start() method of the Thread class to start the thread. Call the join() method of the Thread class to wait for the thread to complete in the main thread.

How would you execute function in a separate new thread with the module thread?

First, we must create a new instance of the threading. Thread class and specify the function we wish to execute in a new thread via the “target” argument. The function executed in another thread may have arguments in which case they can be specified as a tuple and passed to the “args” argument of the threading.

How do you extend a thread in Python?

Thread class can be extended to run code in another thread. This can be achieved by first extending the class, just like any other Python class. Then the run() function of the threading. Thread class must be overridden to contain the code that you wish to execute in another thread.


1 Answers

You can subclass directly from Thread in this 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
        # 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()