gpt4 book ai didi

python - 异步键盘中断和多线程

转载 作者:太空宇宙 更新时间:2023-11-03 19:25:46 25 4
gpt4 key购买 nike

Python 似乎无法正确处理多线程程序中的异步信号。但是,我想我应该在这里检查一下,看看是否有人能发现我违反某些原则或误解某些概念的地方。

我在 SO 上找到了类似的线程,但似乎没有一个完全相同。

场景是:我有两个线程,读取器线程和写入器线程(主线程)。写入器线程写入读取器线程轮询的管道。这两个线程使用 threading.Event() 原语进行协调(我假设它是使用 pthread_cond_wait 实现的)。主线程等待 Event,而读取器线程最终设置它。

但是,如果我想在主线程等待 Event 时中断程序,则不会异步处理 KeyboardInterrupt。

这是一个小程序来说明我的观点:

#!/usr/bin/python
import os
import sys
import select
import time
import threading

pfd_r = -1
pfd_w = -1
reader_ready = threading.Event()

class Reader(threading.Thread):
"""Read data from pipe and echo to stdout."""
def run(self):
global pfd_r
while True:
if select.select([pfd_r], [], [], 1)[0] == [pfd_r]:
output = os.read(pfd_r, 1000)
sys.stdout.write("R> '%s'\n" % output)
sys.stdout.flush()
# Suppose there is some long-running processing happening:
time.sleep(10)
reader_ready.set()


# Set up pipe.
(pfd_r, pfd_w) = os.pipe()
rt = Reader()
rt.daemon = True
rt.start()

while True:
reader_ready.clear()
user_input = raw_input("> ").strip()
written = os.write(pfd_w, user_input)
assert written == len(user_input)
# Wait for reply -- Try to ^C here and it won't work immediately.
reader_ready.wait()

使用“./bug.py”启动程序并在提示符下输入一些内容。一旦您看到读者回复前缀“R>”,请尝试使用 ^C 打断。

我所看到的(Ubuntu Linux 10.10、Python 2.6.6)是,直到阻塞 reader_ready.wait() 返回之后才处理 ^C 。我期望看到的是 ^C 异步引发,导致程序终止(因为我没有捕获 KeyboardInterrupt)。

这可能看起来像是一个人为的示例,但我在现实世界的程序中遇到了这个问题,其中 time.sleep(10) 被实际计算取代。

我是否做了一些明显错误的事情,例如误解了预期结果?

编辑:我也刚刚使用 Python 3.1.1 进行了测试,也存在同样的问题。

最佳答案

wait()方法threading._Event对象实际上依赖于 thread.lockacquire()方法。然而,thread documentation指出锁的 acquire()方法不能被中断,并且任何KeyboardInterrupt释放锁后会处理异常。

所以基本上,这是按预期工作的。实现此行为的线程对象依赖于某个点(包括队列)的锁,因此您可能需要选择其他路径。

关于python - 异步键盘中断和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8184051/

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