【发布时间】:2019-05-10 21:15:28
【问题描述】:
我有一个子类threading.Thread 的类。它的唯一职责就是将从 UNIX 命名管道读取的消息放入 queue.Queue 对象(以便其他线程稍后可以处理这些值)。
示例代码:
class PipeReaderThread(Thread):
def __init__(self, results_queue, pipe_path):
Thread.__init__(self)
self._stop_event = Event()
self._results_queue = results_queue
self._pipe_path = pipe_path
def run(self):
while not self._stop_event.is_set():
with open(self._pipe_path, 'r') as pipe:
message = pipe.read()
self._results_queue.put(message, block=True)
def stop(self):
self._stop_event.set()
如您所见,我想使用 threading.Event 对象来停止循环,但是由于命名管道上的 open() 或 read() 调用将阻塞(直到有人打开管道以进行写入/写入然后关闭它),线程永远没有机会停止。
我不想对命名管道使用非阻塞模式,因为阻塞实际上是我想要的,从某种意义上说,我想等待有人打开并写入管道。
对于套接字,我会尝试在套接字上设置超时标志,但我找不到任何方法来为命名管道执行此操作。 我也考虑过只是冷血地杀死线程而不给它一个优雅地停止的机会,但这并不是我应该做的事情,我什至不知道 Python 是否提供任何这样做的方法.
我应该如何正确停止这个线程,以便之后我可以调用join()?
【问题讨论】:
标签: python-3.x multithreading pipe named-pipes blocking