RfD: Automagically making a class instance 'synchronized' (draft impl.)
Gerhard Häring
gh_pythonlist at gmx.de
Tue Jun 11 16:54:23 EDT 2002
For one of my projects, I'll need something not quite unlike the
following code. It's not tested, yet, but it looks ok and complete to
me. I thought that it could be useful to other developers who need to
use multithreading, so I'm posting it here. Maybe something like this
would even be a useful addition to the Standard Library?
Gerhard
from threading import RLock
class Connection:
def begin(self):
print "begin"
def commit(self):
print "commit"
class LockingWrapper:
def __init__(self, proxy, obj):
self.proxy = proxy
self.obj = obj
def __call__(self, *args, **kwargs):
self.proxy.__dict__["rlock"].acquire(1)
try:
self.obj(*args, **kwargs)
except:
self.proxy.__dict__["rlock"].release()
raise
return
self.proxy.__dict__["rlock"].release()
class LockingProxy:
"""LockingProxy proxies an instance of a class, so that in that instance,
only one method can be active at any given point in time. In Java-speak, it
automatically makes all methods of this class 'synchronized'."""
def __init__(self, obj, methodnames):
"""obj -> a callable
methodnames -> a list of method names"""
self.__dict__["obj"] = obj
self.__dict__["rlock"] = RLock()
self.__dict__["methodnames"] = methodnames
def __getattr__(self, attr):
val = getattr(self.__dict__["obj"], attr)
if attr not in self.__dict__["methodnames"]:
return val
else:
return LockingWrapper(self, val)
conn = Connection()
lp = LockingProxy(conn, ["begin", "commit"])
lp.begin()
--
This sig powered by Python!
Außentemperatur in München: 16.6 °C Wind: 0.6 m/s
More information about the Python-list
mailing list