作者:le__citron | 来源:互联网 | 2022-11-25 19:26
我有一个子类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()
在之后调用它?