我有一个子类 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() ?