【发布时间】:2023-03-14 17:27:02
【问题描述】:
我试图在不直接引用线程的情况下结束线程执行。因为在整个程序中不可能做到这一点。 作为参考,主程序适用于 Raspberry Pi,我需要它在按下按钮后立即停止执行函数/线程。
我尝试从 main 引发异常,但另一个由于某种原因没有捕获它。
这是我一直在测试的报废程序:
import threading
import time
class Thread_Exception(Exception):
def __init__(self, msg):
return super().__init__(msg)
def thread_function(index):
bool = True
try:
while bool:
print("Print from thread #", index)
time.sleep(4)
except Thread_Exception:
print('Exception thrown, thread #', index)
bool = False
if __name__ == "__main__":
try:
for index in range(3):
x = threading.Thread(target=thread_function, args=(index,))
x.start()
time.sleep(20)
raise Thread_Exception("intr")
while True:
continue
except KeyboardInterrupt:
print('Interrupted main')
【问题讨论】:
标签: python multithreading exception raspberry-pi