python - python 中的线程 exit_request

标签 python multithreading

我有一个调用线程对象的主页,该对象正在进行一些测量,但有时如果出现问题,我希望主页停止线程。

我正在做这样的事情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()

thread.exit()

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/

相关文章:

c# - Windows IoT上的多线程导致线程关闭

python - Tkinter动态 "iframe"不会滚动

python - 将字符串打印为 HTML

python - 设置 restrict_xpaths 设置后出现 UnicodeEncodeError

python - 如何手动卸载openerp模块

Python + PyCharm 文件结构问题 : AttributeError: 'module' object has no attribute 'X'

c - C语言线程,跨平台

android - 暂停线程 - HistoryRecord 的 Activity 暂停超时

c++ - 在 OpenCL 内核中使用 OpenGL

multithreading - Tomcat 7 异步处理