[Baypiggies] Synchronized in Python

Shannon -jj Behrens jjinux at gmail.com
Mon Dec 3 11:10:21 CET 2007

On Nov 25, 2007 8:47 AM, Aahz <aahz at pythoncraft.com> wrote:
> On Sun, Nov 11, 2007, Monte Davidoff wrote:
> >
> > Stephen McInerney and I were talking after the last BayPIGgies meeting
> > (Concurrency in Python) and thought it might be of help to post how to
> > get the effect of the Java synchronized keyword in Python.  (I arrived a
> > little late, so perhaps this was mentioned before I got there.)  This
> > post is meant as a quick example, so the explanation is brief and I hope
> > not too confusing.  In Java, the synchronized keyword ensures that only
> > one thread is executing a method or block at a time.
> Generally speaking, my recommendation is that you ensure that only one
> thread has access to an object at any time.  It's much simpler.  Just use
> a queue to pass objects between threads.  You can find examples in my
> thread tutorial slides.

I agree.  That's my favorite approach as well.

/me giggles:
I also like passing function references via the queue as well.  It's
like, "Here, call this function, but call it on your thread." ;)

> Another heavy-weight option is to allow only one thread at a time to
> access attributes or methods within a class.  I don't have example code
> handy, but you override __getattribute__ to do the locking, roughly the
> same way that Monte describes for individual sections.  It gets a bit
> tricky with methods, and I think you may need to use a metaclass to get
> it right.  (IOW, I recommend against this approach, but I mention it in
> case someone finds it useful.)

In the past, I've found it helpful to do assertions on the thread name
to make sure that certain methods only ever get called from what I
think is the right thread.  Just an idea.

Happy Hacking!

I, for one, welcome our new Facebook overlords!

More information about the Baypiggies mailing list