From faba368ee235609ed7ff9d32bbf0a892eef0ddb2 Mon Sep 17 00:00:00 2001 From: Constantin Berhard Date: Sun, 27 Oct 2013 11:14:59 +0100 Subject: [PATCH 1/1] concept spaceAPI + Locking --- concept_spaceapi.py | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/concept_spaceapi.py b/concept_spaceapi.py index 472b26d..0f251d7 100644 --- a/concept_spaceapi.py +++ b/concept_spaceapi.py @@ -1,24 +1,40 @@ - +from threading import Lock class SpaceApi: __init__ (self, waker): - self._state_to_set = None # public write - self._state_last_set = None # public read FIXME why? getter? + self._state_to_set = None + self._state_last_set = None self._running = True self.set_state = ThreadFunction(self._set_state, "Space API") + self._set_state_lock = Lock() waker.register(self.set_state, 10.0) # re-try setting the state every 10 seconds def stop (self): self.set_state.stop() + # set_state is the asynchronous version of _set_state (see __init__) def _set_state (self, state = None): '''Sets the state, if None: leave state unchanged and re-try if previous attempts failed''' if state is not None: self._state_to_set = state - # check if there's something we need to do - if self._state_last_set == self._state_to_set: return - # take action! - error = do_request(stts) # TODO - #TODO logging - if not error: - self.state_last_set = stts + else: + # always have a local variable because of parallelism + state = self._state_to_set + + if not self._set_state_lock.acquire(False): + # we don't want many threads to wait here + # the next status update will fix everything anyways + pass + else: + # got the lock + try: + # check if there's something we need to do + if self._state_last_set == state: return + # take action! + error = do_request(stts) # TODO + #TODO logging + #TODO error too often -> log critical to send mails + if not error: + self.state_last_set = stts + finally: + self._set_state_lock.release() -- 2.30.2