python - 如何在python中的线程循环中引发异常?

标签 python multithreading loops exception

我正在寻找一种在True True循环中引发异常的方法。引发异常的信号起源于线程t_run,该线程连续检查称为pingresponse的全局 bool 变量。当pingresponse等于“False”时,while True循环应立即中断。我不想要的是在while True循环中连续检查变量pingresponse,以检查是否必须引发异常。
到目前为止,我的草稿如下:

import time
import threading
import random

def run():
    # this thread continuously checks the pingresponse
    global pingresponse

    while True:
        # simulating a random pingresponse
        if random.random() > 0.8:
            pingresponse = False
        else:
            pingresponse = True
        time.sleep(0.001)

pingresponse = True
t_run = threading.Thread(target=run)
t_run.start()

while True:
    i = 0
    while True:
        try:
            print('While True loop iteration', i)
            print('pingresponse:' ,pingresponse)
            i += 1

            # "do some work" which includes several consecutive and encapsulated while and for loops
            time.sleep(1) # simulate "do some work" and prevent infinite looping if executed

            # What I want is immediately interrupting the inner while True loop by raising an exception
            # as soon as pingresponse was set to False in the t_run thread
            # The exception should be raised independently of the current position in "do some work"

            # What I don't want is to check the pingresponse variable all the time in "do some work":
            # if not pingresponse:
            #   raise Exception

        except Exception:
            print('pingresponse was set to False in the t_run thread')
            print('start while True loop again with iteration 0')
            break

最佳答案

this answerHow to exit the entire application from a Python thread?的使用方法。将您的示例修改为,在发生异常时停止所有_thread.interrupt_main()将在主线程中引发键盘中断。

import time
import threading
import _thread
import random

def run():
    # this thread continously checks the pingresponse
    global pingresponse

    while True:
        # simulating a random pingresponse
        x = random.random()
        print(f'x:{x:1.3f}')
        if x > 0.98:
            pingresponse = False
        else:
            pingresponse = True
        time.sleep(0.001)
        if not pingresponse:
            _thread.interrupt_main()
            break

pingresponse = True
t_run = threading.Thread(target=run)
t_run.start()

foo = True
while foo:
    i = 0
    while True:
        try:
            print('While True loop iteration', i)
            print('pingresponse:' ,pingresponse)
            i += 1

            # "do some work" which includes several consecutive and encapsulated while and for loops
            time.sleep(1) # simulate "do some work" and prevent infinite looping if executed

        except KeyboardInterrupt as e:
            print('pingresponse was set to False in the t_run thread')
            print('start while True loop again with iteration 0')
            # print(e)
            foo = False
            # raise
            break
    if foo: break

如果使用_thread.interrupt_main(),可能需要考虑一些事情-您应该花一些时间进行研究。可能希望在此旅程中包括signal module
How do I capture SIGINT in Python?看起来很值得。

关于python - 如何在python中的线程循环中引发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65457487/

相关文章:

python - 线程API调用导致Nonce错误的解决方案?

C++陷入死循环

python - Django 中的 Xlwt 导出显示错误信息

python - 使用许多分隔符分隔字符串(列表元素),而不会丢失列表中的碎片

java - 如何使用不同的实现异步调用多个方法

java - 将递归函数转换为 for 循环?

javascript - 创建一个函数来编辑具有可变数字和给定字符串的列表

Python + 散点图 + 其他废话

python - win32com + Outlook 每次执行仅捕获收件箱中 50% 的邮件

c++ - 多个连接更新同一个表