Python 在线程中传播系统调用中断
我正在运行两个python线程(Python 在线程中传播系统调用中断,python,multithreading,system-calls,interrupted-exception,Python,Multithreading,System Calls,Interrupted Exception,我正在运行两个python线程(导入线程)。它们都在open()调用中被阻止;事实上,它们试图打开命名管道以便在其中写入,因此在有人尝试从命名管道读取之前进行阻止是一种正常的行为 简言之,它看起来像: import threading def f(): open('pipe2', 'r') if __name__ == '__main__': t = threading.Thread(target=f) t.start() open('pipe1', 'r')
导入线程
)。它们都在open()
调用中被阻止;事实上,它们试图打开命名管道以便在其中写入,因此在有人尝试从命名管道读取之前进行阻止是一种正常的行为
简言之,它看起来像:
import threading
def f():
open('pipe2', 'r')
if __name__ == '__main__':
t = threading.Thread(target=f)
t.start()
open('pipe1', 'r')
当我键入^C时,主线程中的open()
被中断(引发IOError
,errno==4)
我的问题是:
t
线程仍在等待,我想传播中断行为,以便使它也引发IOError
。我在python文档中发现了这一点:" …只有主线程可以设置新的信号处理程序,并且主线程将是唯一接收信号的线程(这由Python信号模块强制执行,即使底层线程实现支持向单个线程发送信号)。这意味着信号不能用作线程间通信的手段。请改用锁。 “
也许您还应该检查这些文档:
另一个想法是使用select在线程中异步读取管道。这适用于Linux,但不确定Windows(它不是最干净的,也不是最好的实现):
如果在启动子线程之前在子线程中设置daemon=True会发生什么?仅此而已。而且,我的问题的目的不是杀死线程,我希望他在收到信号后做一些事情(清理)。
#!/usr/bin/python
import threading
import os
import select
def f():
f = os.fdopen(os.open('pipe2', os.O_RDONLY|os.O_NONBLOCK))
finput = [ f ]
foutput = []
# here the pipe is scanned and whatever gets in will be printed out
# ...as long as 'getout' is False
while finput and not getout:
fread, fwrite, fexcep = select.select(finput, foutput, finput)
for q in fread:
if q in finput:
s = q.read()
if len(s) > 0:
print s
if __name__ == '__main__':
getout = False
t = threading.Thread(target=f)
t.start()
try:
open('pipe1', 'r')
except:
getout = True