1

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.

  • Alex Martelli answered to [this question](https://stackoverflow.com/questions/2291069/is-python-variable-assignment-atomic) that "Simple assignment to simple variables is atomic AKA threadsafe". This would imply that a boolean is good enough even with multithreaded read/write access to it, in a case like yours where you don't need the `wait()` mechanism. The info seems very dependent on the implementation though (CPython?), and reverse engineered from what the [bytecode](http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm) does. – Jeronimo Jul 17 '18 at 06:22
  • @Jeronimo - I think I'll stick with `Event` as it is thread-safe out of the box. –  Jul 17 '18 at 13:43

0 Answers0