Python 如何使用无限循环的目标函数创建可停止线程
假设我想在一个线程中运行一个名为Python 如何使用无限循环的目标函数创建可停止线程,python,python-multithreading,Python,Python Multithreading,假设我想在一个线程中运行一个名为run_forever(),但仍然可以通过按Ctrl+C来“停止”它。我已经看到了使用threading.thread的StoppableThread子类的方法,但这些方法似乎涉及到将目标函数“复制”到该子类中。相反,我希望保留函数“它所在的位置” 考虑以下示例: import time import threading def run_forever(): # An externally defined function which runs indefin
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()
目标函数永远运行
本身就是一个while循环,永远不会退出。但是,要获得所需的行为,wait()
命令必须位于while循环中,据我所知
有没有办法在不修改永远运行()函数的情况下实现所需的行为?我怀疑这是可能的。
顺便说一句,你试过第二种解决方案吗
ThreadWithExc
来自您先前链接的链接?
如果循环忙于纯Python(例如nosleep
),它就会工作,否则我会切换到multiprocessing
并终止子进程。下面是希望优雅退出的代码(*仅限nix):
如果您只想通过按Cntrl+C使程序“可停止”—我将其解释为“在尝试终止程序时不会挂起”—您可以将Thread对象中的daemon属性设置为True:Thread=StoppableThread(daemon=True)
,我已经有了一个使用守护线程的实现,但这些都突然停止了。我想要一些优雅地停止的东西。如果您绝对无法更改永远运行
函数,我认为您最好的机会是直接访问平台API,类似于这里答案中的第二个示例:
from multiprocessing import Process
from signal import signal, SIGTERM
import time
def on_sigterm(*va):
raise SystemExit
def fun():
signal(SIGTERM, on_sigterm)
try:
for i in xrange(5):
print 'tick', i
time.sleep(1)
finally:
print 'graceful cleanup'
if __name__=='__main__':
proc = Process(target=fun)
proc.start()
time.sleep(2.5)
proc.terminate()
proc.join()