concept spaceAPI + Locking
authorConstantin Berhard <constantin@exxxtremesys.lu>
Sun, 27 Oct 2013 10:14:59 +0000 (11:14 +0100)
committerConstantin Berhard <constantin@exxxtremesys.lu>
Sun, 27 Oct 2013 10:14:59 +0000 (11:14 +0100)
concept_spaceapi.py

index 472b26d490819a39475e0a83459e71b0be3f6551..0f251d7d4b3c1e3b065566ef407c0180c4a62ba4 100644 (file)
@@ -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()