Add support for an on_stop callback

This commit is contained in:
Kristóf Tóth 2019-05-09 13:46:31 +02:00
parent 8f80f49a86
commit 38c81e0d29
2 changed files with 11 additions and 0 deletions

View File

@ -12,6 +12,7 @@ if __name__ == "__main__":
pipe_io = EchoPipeIOServer('in', 'out') pipe_io = EchoPipeIOServer('in', 'out')
signal(SIGTERM, lambda a, b: pipe_io.stop()) signal(SIGTERM, lambda a, b: pipe_io.stop())
signal(SIGINT, lambda a, b: pipe_io.stop()) signal(SIGINT, lambda a, b: pipe_io.stop())
pipe_io.on_stop = lambda: print('Stopping...')
pipe_io.start() pipe_io.start()
print('Running pipe IO server with named pipes:') print('Running pipe IO server with named pipes:')
print(f'Input: {pipe_io.in_pipe}') print(f'Input: {pipe_io.in_pipe}')

View File

@ -1,5 +1,6 @@
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from threading import Thread, Event from threading import Thread, Event
from typing import Callable
from .pipe_reader_thread import PipeReaderThread from .pipe_reader_thread import PipeReaderThread
from .pipe_writer_thread import PipeWriterThread from .pipe_writer_thread import PipeWriterThread
@ -15,6 +16,7 @@ class PipeIOServer(ABC, Thread):
self._stop_event = Event() self._stop_event = Event()
self._reader_thread, self._writer_thread = self._create_io_threads() self._reader_thread, self._writer_thread = self._create_io_threads()
self._io_threads = (self._reader_thread, self._writer_thread) self._io_threads = (self._reader_thread, self._writer_thread)
self._on_stop = lambda: None
def _create_pipes(self, permissions): def _create_pipes(self, permissions):
Pipe(self.in_pipe).recreate(permissions) Pipe(self.in_pipe).recreate(permissions)
@ -58,6 +60,14 @@ class PipeIOServer(ABC, Thread):
thread.stop() thread.stop()
Pipe(self.in_pipe).remove() Pipe(self.in_pipe).remove()
Pipe(self.out_pipe).remove() Pipe(self.out_pipe).remove()
self._on_stop()
def _set_on_stop(self, value):
if not isinstance(value, Callable):
raise ValueError("Supplied object is not callable!")
self._on_stop = value
on_stop = property(fset=_set_on_stop)
def wait(self): def wait(self):
self._stop_event.wait() self._stop_event.wait()