Stopping threads and processes

As mentioned before, in general, stopping a thread is a bad idea, and the same goes for a process. Being sure you've taken care to dispose and close everything that is open can be quite difficult. However, there are situations in which you might want to be able to stop a thread, so let me show you how to do it:

# stop.py
import threading
from time import sleep

class Fibo(threading.Thread):
def __init__(self, *a, **kwa):
super().__init__(*a, **kwa)
self._running = True

def stop(self):
self._running = False

def run(self):
a, b = 0, 1
while self._running:
print(a, end=' ')
a, b = b, a + b
sleep(0.07)
print()

fibo = Fibo()
fibo.start()
sleep(1)
fibo.stop()
fibo.join()
print('All done.')

For this example, we use a Fibonacci generator. We've seen it before so I won't explain it. The important bit to focus on is the _running attribute. First of all, notice the class inherits from Thread. By overriding the __init__ method, we can set the _running flag to True. When you write a thread this way, instead of giving it a target function, you simply override the run method in the class. Our run method calculates a new Fibonacci number, and then sleeps for about 0.07 seconds.

In the last block of code, we create and start an instance of our class. Then we sleep for one second, which should give the thread time to produce about 14 Fibonacci numbers. When we call fibo.stop(), we aren't actually stopping the thread. We simply set our flag to False, and this allows the code within run to reach its natural end. This means that the thread will die organically. We call join to make sure the thread is actually done before we print All done. on the console. Let's check the output:

$ python stop.py
0 1 1 2 3 5 8 13 21 34 55 89 144 233
All done.

Check how many numbers were printed: 14, as predicted.

This is basically a workaround technique that allows you to stop a thread. If you design your code correctly according to multithreading paradigms, you shouldn't have to kill threads all the time, so let that need become your alarm bell that something could be designed better.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.47.221