Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping thread in python3

Tags:

python-3.x

How can I better write the following class? For example is there a nice way to slip having the two flags is_alive and is_finished?

Monitor(threading.Thread):
    def run(self):
        resource = Resource("com1")

        self.alive = True
        self.is_finished = False
        try:
            while self.alive:
                pass # use resource
        finally:
            resource.close()
            self.is_finished = True    

    def stop(self):
        self.alive = False
        while not self.is_finished:
            time.sleep(0.1)
like image 260
Baz Avatar asked Oct 18 '11 11:10

Baz


People also ask

How do you exit a thread in Python?

We can close a thread by returning from the run function at any time. This can be achieved by using the “return” statement in our target task function. If the threading. Thread class has been extended and the run() function overridden, then the “return” statement can be used in the run() function directly.

How do you terminate a thread?

A thread automatically terminates when it returns from its entry-point routine. A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation.

How do you pause a thread in Python?

You can suspend the calling thread for a given time in Python using the sleep method from the time module. It accepts the number of seconds for which you want to put the calling thread on suspension for.

How do you stop and start a thread in Python?

Event can be checked via the is_set() function. The main thread, or another thread, can then set the event in order to stop the new thread from running. The event can be set or made True via the set() function. Now that we know how to stop a Python thread, let's look at some worked examples.


1 Answers

That's pretty much it. However, you don't need the is_finished, because you can use the join() method:

Monitor(threading.Thread):
    def run(self):
        resource = Resource("com1")

        self.alive = True
        try:
            while self.alive:
                pass # use resource
        finally:
            resource.close()

    def stop(self):
        self.alive = False
        self.join()

If you do need to find if a thread is running, you can call mythread.is_alive() - you don't need to set this yourself.

like image 144
Thomas K Avatar answered Oct 21 '22 08:10

Thomas K