我想向 Thread 子类添加一个新方法,这样我就可以告诉我的工作线程优雅地退出。像这样:
class MyThread(threading.Thread):
def __init__(self):
...
self.__stop_signal = False
self.__signal_lock = threading.Lock()
...
def run(self):
...
self.__signal_lock.acquire(True)
stop_signal = self.__stop_signal
self.__signal_lock.release()
if stop_signal:
return
...
def stop_elegantly(self):
self.__signal_lock.acquire(True)
self.__stop_signal = True
self.__signal_lock.release()
那么这样做是否安全?
thread = MyThread()
thread.start()
...
thread.stop_elegantly()
谢谢。