避免退出时,output阻塞退出

This commit is contained in:
Jerry Yan 2022-06-06 17:22:57 +08:00
parent 5d2b86d8e7
commit 2444545dc1
2 changed files with 15 additions and 2 deletions

View File

@ -31,6 +31,7 @@ class OutputManager():
} }
_writer: "List[IOutput]" = [] _writer: "List[IOutput]" = []
_thread: "Optional[threading.Thread]"= None _thread: "Optional[threading.Thread]"= None
_should_exit = threading.Event()
def __init__(self): def __init__(self):
_config = config()['output']['use'] _config = config()['output']['use']
@ -107,14 +108,22 @@ class OutputManager():
writer.error_output(message.method, message.payload, e) writer.error_output(message.method, message.payload, e)
def start_loop(self): def start_loop(self):
self._should_exit.clear()
self._thread = threading.Thread(target=self._handle) self._thread = threading.Thread(target=self._handle)
self._thread.start() self._thread.start()
def _handle(self): def _handle(self):
while True: while True:
message = MESSAGE_QUEUE.get() message = MESSAGE_QUEUE.get()
if self._should_exit.is_set():
break
if message is None:
continue
self.decode_payload(message) self.decode_payload(message)
def terminate(self): def terminate(self):
self._should_exit.set()
MESSAGE_QUEUE.put(None)
for writer in self._writer: for writer in self._writer:
writer.terminate() writer.terminate()

View File

@ -1,4 +1,8 @@
from queue import SimpleQueue from queue import SimpleQueue
from proxy.common import MessagePayload from typing import TYPE_CHECKING
MESSAGE_QUEUE: "SimpleQueue[MessagePayload]" = SimpleQueue() if TYPE_CHECKING:
from typing import Optional
from proxy.common import MessagePayload
MESSAGE_QUEUE: "SimpleQueue[Optional[MessagePayload]]" = SimpleQueue()