pipe-io-server/pipe_io_server/pipe_io_server.py

61 lines
1.7 KiB
Python
Raw Normal View History

from abc import ABC, abstractmethod
2019-04-10 10:40:51 +00:00
from threading import Thread, Event
2018-12-13 21:06:13 +00:00
from .pipe_reader_thread import PipeReaderThread
from .pipe_writer_thread import PipeWriterThread
from .pipe import Pipe
2019-04-10 10:40:51 +00:00
from .terminate_process_on_failure import terminate_process_on_failure
2018-12-13 21:06:13 +00:00
2019-04-10 10:40:51 +00:00
class PipeIOServer(ABC, Thread):
2018-12-13 21:06:13 +00:00
def __init__(self, in_pipe=None, out_pipe=None):
2019-04-10 10:40:51 +00:00
super().__init__()
self._in_pipe, self._out_pipe = in_pipe, out_pipe
2018-12-13 21:06:13 +00:00
self._create_pipes()
self._stop_event = Event()
self._reader_thread, self._writer_thread = self._create_io_threads()
self._io_threads = (self._reader_thread, self._writer_thread)
2018-12-13 21:06:13 +00:00
def _create_pipes(self):
Pipe(self.in_pipe).recreate()
Pipe(self.out_pipe).recreate()
2018-12-13 21:06:13 +00:00
@property
def in_pipe(self):
return self._in_pipe
@property
def out_pipe(self):
return self._out_pipe
def _create_io_threads(self):
reader_thread = PipeReaderThread(self.in_pipe, self._stop_event, self.handle_message)
writer_thread = PipeWriterThread(self.out_pipe, self._stop_event)
return reader_thread, writer_thread
2018-12-16 18:04:51 +00:00
@abstractmethod
2018-12-16 18:16:01 +00:00
def handle_message(self, message):
raise NotImplementedError()
def send(self, message):
self._writer_thread.write(message)
2018-12-13 21:44:46 +00:00
2019-04-10 10:40:51 +00:00
@terminate_process_on_failure
2018-12-13 21:06:13 +00:00
def run(self):
2018-12-13 21:44:46 +00:00
for thread in self._io_threads:
2018-12-13 21:06:13 +00:00
thread.start()
self._stop_event.wait()
self._stop()
2018-12-13 21:06:13 +00:00
def stop(self):
self._stop_event.set()
2019-04-10 10:40:51 +00:00
if self.is_alive():
self.join()
def _stop(self):
2018-12-13 21:44:46 +00:00
for thread in self._io_threads:
if thread.is_alive():
thread.stop()
Pipe(self.in_pipe).remove()
Pipe(self.out_pipe).remove()