mutex? protecting global data/critical section

Skip Montanaro skip at
Fri Sep 19 22:23:58 CEST 2003

    Brian> I am trying to protect some global data, which may, in the
    Brian> future, be accessed by threads. I'm not sure how to implement a
    Brian> locking mechanism in python.

There's generally no need to roll your own locking.  Start simple (Queue
module) and get more sophisticated (threading module's Lock, RLock,
Semaphore, Condition or Event classes).  Almost all the time, a Queue object
will do the trick:

    class resourceManager(object):
      def __init__(self):
       self.__queue = Queue.Queue()
       for i in range(100)

      def getResource(self):
       do my thing

In the above case, you're not actually sharing anything, just using
self.__queue to limit the number of simultaneous threads.  More likely, you
will either have a certain number of objects which are limited by the
performance of your system (say, database connections) or some piece of
global state which you need to control access to (e.g., some kind of
blackboard object).  Either one might look something like this:

    class resourceManager(object):
      def __init__(self, list_of_stuff):
       self.__queue = Queue.Queue()
       for item in list_of_stuff

      def apply(self, func):
       item = self.__queue.get()
       result = func(item)
       return result

    manager = resourceManager([blackboard])

    dbmanager = resourceManager([conn1, conn2, conn3])

Of course, you will probably want a bit more general apply() method so you
can pass other arguments to the function.


More information about the Python-list mailing list