@synchronized dect'r &c.

Paul McGuire ptmcg at austin.rr.com
Sun Feb 24 01:19:40 CET 2008

On Feb 23, 2:03 pm, castiro... at gmail.com wrote:
> 1)  @synchronized
> @synchronized
> def function( arg ):
>    behavior()
> Synchronized prevents usage from more than one caller at once: look up
> the function in a hash, acquire its lock, and call.
> def synchronized( func ):
>    def presynch( *ar, **kwar ):
>       with _synchlock:
>          lock= _synchhash.setdefault( func, allocate_lock() )
>          with lock:
>             return func( *ar, **kwar )
>    return presynch

No need for a global _synchhash, just hang the function lock on the
function itself:

def synch(f):
    f._synchLock = Lock()
    def synchedFn(*args, **kwargs):
        with f._synchLock:
            f(*args, **kwargs)
    return synchedFn

You might also look at the PythonDecoratorLibrary page of the Python
wiki, there is a synchronization decorator there that allows the
function caller to specify its own lock object (in case a single lock
should be shared across multiple functions).

-- Paul

More information about the Python-list mailing list