Preventing tread collisions

Wanderer wanderer at dialup4less.com
Thu Dec 13 17:36:55 CET 2012


On Wednesday, December 12, 2012 3:53:28 PM UTC-5, MRAB wrote:
> On 2012-12-12 20:11, Wanderer wrote:
> 
> > I have a program that has a main GUI and a camera. In the main GUI, you can manipulate the images taken by the camera. You can also use the menu to check the camera's settings. Images are taken by the camera in a separate thread, so the long exposures don't block the GUI. I block conflicts between the camera snapshot thread and the main thread by setting a flag called self.cameraActive. I check to see if the cameraActive flag is false and set the cameraActive to True just before starting the thread. I generate an event on exiting the thread which sets the cameraActive flag to False. I also check and set and reset the flag in all the menu commands that access the camera. Like this.
> 
> >
> 
> >      def onProperties(self, event):
> 
> >          """ Display a message window with the camera properties
> 
> >          event -- The camera properties menu event
> 
> >          """
> 
> >          # Update the temperature
> 
> >          if not self.cameraActive:
> 
> >              self.cameraActive = True
> 
> >              self.camera.getTemperature()
> 
> >              camDict = self.camera.getPropertyDict()
> 
> >              self.cameraActive = False
> 
> >          else:
> 
> >              camDict = {'Error': 'Camera Busy'}
> 
> >          dictMessage(camDict, 'Camera Properties')
> 
> >
> 
> > This works but my question is, is there a better way using semaphores, locks or something else to prevent collisions between threads?
> 
> >
> 
> That suffers from a race condition in that self.cameraActive might be
> 
> False when it's checked in the 'if' condition but set to True just
> 
> afterwards by the other thread.
> 
> 
> 
> You could try a non-blocking semaphore:
> 
> 
> 
> def __init__(self):
> 
>      self.cameraActive = Semaphore()
> 
> 
> 
> def onProperties(self, event):
> 
>      """ Display a message window with the camera properties
> 
>      event -- The camera properties menu event
> 
>      """
> 
>      # Update the temperature
> 
>      if self.cameraActive.acquire(False): # Non-blocking
> 
>          # Successfully acquired the semaphore, so the camera wasn't active
> 
>          self.camera.getTemperature()
> 
>          camDict = self.camera.getPropertyDict()
> 
>          self.cameraActive.release()
> 
>      else:
> 
>          camDict = {'Error': 'Camera Busy'}

Thanks. Why Non-blocking?



More information about the Python-list mailing list