mutex? protecting global data/critical section
Dave Brueck
dave at pythonapocrypha.com
Thu Sep 18 15:49:11 EDT 2003
On Friday 19 September 2003 01:10 pm, Brian Alexander wrote:
> Hello;
>
> I am trying to protect some global data, which may, in the future, be
> accessed by threads. I'm not sure how to implement a locking mechanism
> in python. Here is the idea I'm trying to express:
>
> class resourceManager(object):
> def __init__(self):
> self.__resources = 100
>
> def getResource(self):
> BEGIN CRITICAL SECTION HERE
> if self.__resources > 0:
> self.__resources -= 1
> * other related state information adjusted, too *
> else:
> emergencyCode()
> END CRITICAL SECTION HERE
>
> How is this accomplished? Does anyone know of a simple example?
The basic idiom is to create a lock object somewhere:
lock = threading.Lock()
...
and then your critical section looks like:
lock.acquire()
try:
dostuff
finally:
lock.release()
-Dave
More information about the Python-list
mailing list