Skip to content Skip to sidebar Skip to footer

Is It Safe To Add A New Method To Python Thread Class?

I want to add a new method to a Thread subclass so I can tell my working thread to exit elegantly. Like this: class MyThread(threading.Thread): def __init__(self): ...

Solution 1:

Yes, it looks fine. In fact you could do it even more "elegantly" with:

defstop_elegantly(self):
    with self.__signal_lock:
        self.__stop_signal = True

Actually I don't think you even need a lock to access the member variable since there'll be a separate one allocated for each instance of your subclass. See this answer for example, which adds a stop() method to the threading.Thread subclass.

Solution 2:

self.__signal_lock.acquire(True)
    stop_signal = self.__stop_signal
    self.__signal_lock.release()

The above code is in loop? If yes, I think it works well.

Post a Comment for "Is It Safe To Add A New Method To Python Thread Class?"