Preventing tread collisions

Alexander Blinne news at blinne.net
Thu Dec 13 11:26:47 CET 2012


Am 12.12.2012 21:29, schrieb Dave Angel:
> 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
>>             self.camera.getTemperature()
>>             camDict = self.camera.getPropertyDict()
>>             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.

I have a general question about this kinds of things. I see that the
above is a common use case for some kind of lock which does this
testing/locking atomically. But the question is: if I know for sure that
there is no other thread that might get in the way this solution would
be fine, right?

In one of my applications i have a somewhat different case: i have a
list of objects and call the same method of each object, each in its own
thread (which is created and later joined just for this purpose). The
objects are thus only used by that one thread, the main thread waits for
all threads to be finished before accessing those objects again. Do i
really need some kind of locking for those objects?

Greetings



More information about the Python-list mailing list