我有一个调用线程对象的主页,该对象正在进行一些测量,但有时如果出现问题,我希望主页停止线程。
我正在做这样的事情Is there any way to kill a Thread in Python?
但是这篇文章说
The thread should check the stop flag at regular intervals.
有什么聪明的方法可以做到这一点吗?
我的代码正在进行一些设置,然后对于它必须测量的每个位置都有一个循环,并且在该循环中每次它必须测量每个位置时都有另一个循环。
我一直在做这样的事情:
def run(self):
if EXIT is False:
SETUP
for place in places:
if EXIT is False:
for measurement in measurements:
if EXIT is False:
measure()
else:
break
else:
self.stop()
else:
self.stop()
这只是代码示例,我想要一种更漂亮的方式来检查退出请求,而不是使用所有的 if 语句
谢谢
最佳答案
仅在最内层循环内检查还不够吗?然后您可以抛出异常,而不是检查所有上层的标志。您甚至可以将这一切包装在一个函数中:
def check_thread_exit():
if EXIT:
thread.exit()
block 引用>Raise the SystemExit exception. When not caught, this will cause the thread to exit silently.
然后你的代码就会变成
def run(self): # an optional try-except block to do cleanup at top level try: SETUP for place in places: for measurement in measurements: check_thread_exit() measure() except SystemExit: CLEANUP raise`
关于python - python 中的线程 exit_request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18236155/