Synchronization mixin in Python anyone?
Gustavo Cordova
gcordova at hebmex.com
Fri May 3 17:21:34 EDT 2002
>
> The Zope system contains a Synchronization mixin class
> for thread synchronization written in C. Derive a class from
> Synchronized
> and any mythod calls on an instance of the class are
> thread safe.
>
> Does anybody know of any Python implementation? The C version
> exhibits "interesting" refcounting behavior I need to work around.
>
> regards,
> Sean McGrath
>
Hmmm... interesting problem. I've been playing with a function
synchronization class lately, just toying with the idea. I don't
know if anybody wants it, but here's the basic skeleton:
### SynchronizedCall
import thread
class SynchronizedCall:
def __init__(self, function, *args, **kw):
self._lock = thread.Lock()
self._args = args
self._kw = kw
self._function = function
def __call__(self, *args, **kw):
self._lock.acquire()
try:
args = self._args + args
kw.update(self._kw)
result = self._function(*args, **kw)
## In case of an exception, release lock first.
except:
self._lock.release()
raise
self._lock.release()
return result
## THE END
Really quite simple.
The thing that discouraged me from trying to do this with
instance methods, is that it becomes a bit complicated if
someone takes a reference to a method, like I do commonly:
## Example
rex = sre.compile(r"really big and complicated", sre.S|sre.I)
find_everything = rex.findall
while ... :
...
things = find_everything(string)
...
## End example
So, how would I protect calls to rex.findall() when they're
done through find_everything() ?
Anyway, have fun :-)
-gustavo
More information about the Python-list
mailing list