【发布时间】:2013-11-07 02:48:05
【问题描述】:
我想向 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()
谢谢。
【问题讨论】:
标签: python multithreading