假设我想在一个线程中运行一个名为run_forever()的函数,但是按Ctrl C仍然可以让它“停止”.我已经看到了使用threading.Thread的StoppableThread子类进行此操作的方法,但这些似乎将目标函数“复制”到该子类中.我想保持功能“它在哪里”.
请考虑以下示例:
@H_403_8@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循环中,正如我所理解的那样.
最佳答案
我怀疑这是可能的.
顺便说一句,你有没有尝试过第二个解决方案
您之前链接的the post的ThreadWithExc?
如果循环繁忙的纯Python(例如没有睡眠),它可以工作,否则我会切换到多处理并杀死子进程.这是希望优雅退出的代码(仅限* nix):
顺便说一句,你有没有尝试过第二个解决方案
您之前链接的the post的ThreadWithExc?
如果循环繁忙的纯Python(例如没有睡眠),它可以工作,否则我会切换到多处理并杀死子进程.这是希望优雅退出的代码(仅限* nix):
@H_403_8@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()