59 lines
2.4 KiB
Python
59 lines
2.4 KiB
Python
"""Isolate read-only process-memory reads from bulk work in the control host."""
|
|
import multiprocessing
|
|
import math
|
|
import time
|
|
|
|
|
|
def _read_child(connection,factory):
|
|
reader=factory()
|
|
try:
|
|
while True:
|
|
request=connection.recv()
|
|
if request is None:return
|
|
sample,context=request
|
|
try:result=dict(reader.snapshot(sample,*context))
|
|
except Exception as exc:result=dict(available=False,reason=type(exc).__name__+': '+str(exc))
|
|
connection.send(result)
|
|
except (EOFError,BrokenPipeError,OSError):
|
|
pass
|
|
finally:reader.close();connection.close()
|
|
|
|
|
|
class NativeReaderProcess:
|
|
"""One bounded outstanding read, original request times retained on retries."""
|
|
def __init__(self,factory,*,clock=time.monotonic,context=None):
|
|
context=context or multiprocessing.get_context('spawn')
|
|
self.clock=clock;self._sent_at=None;self._closed=False
|
|
self._source_stamp=self._bound_stamp=None
|
|
self._connection,child=context.Pipe()
|
|
self._process=context.Process(target=_read_child,args=(child,factory),
|
|
name='ATS isolated GPS reader',daemon=True)
|
|
self._process.start();child.close()
|
|
|
|
@property
|
|
def pid(self):return self._process.pid
|
|
|
|
def snapshot(self,sample,*context):
|
|
if self._closed:return dict(available=False,reason='Isolated reader closed')
|
|
if self._sent_at is None:
|
|
self._sent_at=self.clock()
|
|
self._connection.send((sample,context))
|
|
if not self._connection.poll(.3):
|
|
return dict(available=False,reason='Waiting for isolated GPS observation')
|
|
result=dict(self._connection.recv());sent,self._sent_at=self._sent_at,None
|
|
stamp=result.get('sampled_at')
|
|
if isinstance(stamp,(int,float)) and math.isfinite(stamp):
|
|
# A cached child observation must keep its first request bound.
|
|
# Re-polling it cannot move the timestamp toward read completion.
|
|
if stamp!=self._source_stamp:
|
|
self._source_stamp=stamp;self._bound_stamp=min(stamp,sent)
|
|
result['sampled_at']=self._bound_stamp
|
|
result['age_s']=max(0.,self.clock()-result['sampled_at'])
|
|
return result
|
|
|
|
def close(self):
|
|
if self._closed:return
|
|
self._closed=True;self._connection.close()
|
|
if self._process.is_alive():self._process.terminate()
|
|
self._process.join(timeout=.5)
|