假设我想在一个线程中运行一个名为run_forever()的函数,但是按Ctrl C仍然可以让它“停止”.我已经看到了使用threading.Thread的StoppableThread子类进行此操作的方法,但这些似乎将目标函数“复制”到该子类中.我想保持功能“它在哪里”.
请考虑以下示例:
import time
import threading
def run_forever(): # An externally defined function which runs indefinitely
while True:
print("Hello,world!")
time.sleep(1)
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self,*args,**kwargs):
super(StoppableThread,self).__init__(*args,**kwargs)
self._stop = threading.Event()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
def run(self):
while not self.stopped():
run_forever() # This doesn't work
# print("Hello,world!") # This does
self._stop.wait(1)
thread = StoppableThread()
thread.start()
time.sleep(5)
thread.stop()
目标函数run_forever本身就是一个永不退出的while循环.但是,为了获得所需的行为,wait()命令必须在while循环中,正如我所理解的那样.
有没有办法在不修改run_forever()函数的情况下实现所需的行为?