gpt4 book ai didi

未捕获 Python SIGINT

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:08 26 4
gpt4 key购买 nike

我无法理解为什么我的 SIGINT 从未被下面的代码捕获。

#!/usr/bin/env python
from threading import Thread
from time import sleep
import signal

class MyThread(Thread):
def __init__(self):
Thread.__init__(self)
self.running = True

def stop(self):
self.running = False

def run(self):
while self.running:
for i in range(500):
col = i**i
print col
sleep(0.01)

global threads
threads = []

for w in range(150):
threads.append(MyThread())

def stop(s, f):
for t in threads:
t.stop()

signal.signal(signal.SIGINT, stop)

for t in threads:
t.start()

for t in threads:
t.join()

要清理此代码,我更愿意尝试/排除 join() 并在出现异常时关闭所有线程,这样可行吗?

最佳答案

python 中多线程的一个问题是 join() 或多或少地禁用了信号。

这是因为信号只能传递给主线程,但主线程已经忙于执行 join() 并且连接不可中断。

您可以从signal 模块的文档中推断出这一点

Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform signal() operations in the main thread of execution. Any thread can perform an alarm(), getsignal(), pause(), setitimer() or getitimer(); only the main thread can set a new signal handler, and the main thread will be the only one to receive signals (this is enforced by the Python signal module, even if the underlying thread implementation supports sending signals to individual threads). This means that signals can’t be used as a means of inter-thread communication. Use locks instead.

您可以通过忙循环连接操作来解决它:

for t in threads:
while t.isAlive():
t.join(timeout=1)

然而,这不是高效的:

The workaround of calling join() with a timeout has a drawback: Python's threading wait routine polls 20 times a second when given any timeout. All this polling can mean lots of CPU interrupts/wakeups on an otherwise idle laptop and drain the battery faster.

此处提供了更多详细信息:

Python program with thread can't catch CTRL+C

可以在此处找到有关此问题的错误报告以及对潜在问题的讨论:

https://bugs.python.org/issue1167930

https://bugs.python.org/issue1171023

关于未捕获 Python SIGINT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29660830/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com