I came across these two pages (1,2) about cancelling threads.
Example 1 - StackOverflow:
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
Example 2 - Python for Lab:
class OhmLaw:
def __init__(self):
self.data = np.zeros(0) # To store the data of the measurement
self.step = 0 # To keep track of the step
self.running = False
self.stop = False
def make_measurement(self, start, stop, num_points, delay):
# left out additional code to keep example simple.
for i in x_axis:
if self.stop:
print('Stopping')
break
Question:
Is using a boolean
to cancel a thread
bad practice? Is the preferred method to use Event.set()
?
Is there any disadvantage to using the boolean
to cancel?
From the docs:
Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all.
I don't think that can be done with a boolean
alone, however, the docs are for an event
object shared across multiple threads, I don't think you'll use a boolean
for that.