如何在Python中阻止在命名管道上阻塞的线程?

kri*_*pet 6 multithreading pipe named-pipes blocking python-3.x

我有一个子类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()
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我想使用一个threading.Event对象来停止循环,但由于命名管道上的open()read()调用将阻塞(直到有人打开管道写入/写入然后关闭它),线程永远不会有机会停.

我不想对命名管道使用非阻塞模式,因为阻塞实际上是我想要的,我想等待某人打开并写入管道.

使用套接字我会尝试在套接字上设置超时标志,但我找不到任何方法为命名管道执行此操作.我还考虑过用冷血杀死线程而不给它机会优雅地停止,但这并不像我应该做的那样,我甚至不知道Python是否提供了这样做的方法.

我应该如何正确地停止这个线程,以便我可以join()在之后调用它?

zch*_*zch 7

执行此操作的经典方法是使用未命名的管道来表示关闭并使用它select来知道要使用哪个管道。

select将阻塞,直到其中一个描述符可供读取,然后您可以使用os.read在这种情况下不会阻塞的描述符。

演示代码(不处理错误,可能会泄漏描述符):

class PipeReaderThread(Thread):
    def __init__(self, results_queue, pipe_path):
        Thread.__init__(self)
        self._stop_pipe_r, self._stop_pipe_w = os.pipe()
        self._results_queue = results_queue
        self._pipe = os.open(pipe_path, os.O_RDONLY) # use file descriptors directly to read file in parts
        self._buffer = b''

    def run(self):
        while True:
            result = select.select([self._stop_pipe_r, self._pipe], [], [])
            if self._stop_pipe_r in result[0]:
                os.close(self._stop_pipe_r)
                os.close(self._stop_pipe_w)
                os.close(self._pipe)
                return
            self._buffer += os.read(self._pipe, 4096) # select above guarantees read is noblocking
            self._extract_messages_from_buffer() # left as an exercise

    def stop(self):
        os.write(self._stop_pipe_w, b'c')
Run Code Online (Sandbox Code Playgroud)