Preventing tread collisions

Dave Angel d at
Wed Dec 12 21:29:18 CET 2012

On 12/12/2012 03:11 PM, 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
>             camDict =
>             self.cameraActive = False
>         else:
>             camDict = {'Error': 'Camera Busy'}
>         dictMessage(camDict, 'Camera Properties')
> This works 

I don't think so.  in between the if and the assignment, another thread
could get in there and also set the flag.  Then when either one of them
finishes, it'll clear the flag and the other code is unprotected.

For semaphores between multiple threads, you either have to define only
a single thread at any given moment being permitted to modify it, or you
have to use lower-level primitives, sometimes called test+set operation.

i don't know the "right" way to do this in Python, but this isn't it.
> but my question is, is there a better way using semaphores, locks or something else to prevent collisions between threads?
> Thanks



More information about the Python-list mailing list