Synchronization methodology

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Jan 3 03:47:44 EST 2007


In <mailman.2231.1167803272.32031.python-list at python.org>, Chris Ashurst
wrote:

> Hi, I'm coming in from a despised Java background, and I'm having some 
> trouble wrapping my head around sharing an object between multiple 
> instances of a single class (in simpler terms, I would say imagine a 
> simple chat server that has to share a list of connected users to each 
> instance of a connected user).
> 
> Usually, I would have a synchronized list instantiated inside each 
> instance of a client class, which would do the trick, but since there's 
> no synchronization in Python, I'm stuck staring at little tests 
> involving a standalone non-threaded class instance that holds the list 
> of users, and each connected user being passed this instance to be 
> "synchronized".

There's no ``synchronized`` keyword, but of course you can synchronize
methods.  You have to attach an `threading.RLock` to the objects you want
to synchronize on and use its `aquire()` and `release()` methods in places
where you used ``synchronized (someObject) { ... }`` in Java.

synchronized foo() { /* code */ }

is the same as

foo() {
  synchronized (this) { /* code */ }
}

in Java.  And that's basically:

def foo(self):
    self.lock.aquire()
    # code
    self.lock.release()

You may want to make sure the lock will be released in case of an
exception:

def foo(self):
    self.lock.aquire()
    try:
        pass # code
    finally:
        self.lock.release()

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list