Synchronizing methods of a class

Christopher De Vries devries at idolstarastronomer.com
Tue Feb 8 10:02:36 EST 2005


On Mon, Feb 07, 2005 at 11:57:02AM -0800, Keith Veleba wrote:
> Background:
> I'm working on a project where I have to do some serious
> multithreading. I've worked up a decorator in Python 2.3.4 to implement
> the lock semantics required for specific functions I want to
> synchronize:

I found Chris Liechti's example very helpful when working on a similar
project. See
http://groups-beta.google.com/group/comp.lang.python/msg/d647a830de39d1db
. Also, I strongly suggest using threading.RLock() objects instead of primitive
locks. With Rlocks one thread can acquire the same lock multiple times without
blocking. This is useful if one synchronized method calls another synchronized method.

> Obviously, my classes have to instantiate the _lock in __init__ in
> order for this to work.

The great thing about Chris's example is that the first time a synchronized
method is called a lock is instantiated, so you don't have to worry about this
step.

> Problem:
> 
> When iterating through klass.__dict__.items() in the convenience
> method, I only get the instance variables of the class.  No functions.
> I've found a way to get the function list, by iterating through
> klass.__class__.__dict__ .

I'm not sure why klass.__dict__.items() isn't working for you. I tried a simple
example:

class simple(object):
    def hello(self):
        print "Hello World"

def methods(cls):
    for name,value in cls.__dict__.items():
        if callable(value):
            print name

>>> methods(simple)
hello


Chris



More information about the Python-list mailing list