[Baypiggies] Synchronized in Python

Aahz aahz at pythoncraft.com
Sun Nov 25 17:47:49 CET 2007


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.

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.)
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"Typing is cheap.  Thinking is expensive."  --Roy Smith


More information about the Baypiggies mailing list