Simple thread-safe counter?
Heiko Wundram
modelnine at ceosg.de
Sat Apr 2 17:57:52 EST 2005
Am Samstag, 2. April 2005 22:28 schrieb Paul Rubin:
> I'm starting to believe the GIL covers up an awful lot of sloppiness
> in Python. I wonder if there could be a decorator approach:
>
> @synchronized
> def counter():
> t = itertools.count()
> while True:
> yield t.next()
Of course there could:
def synchronized_iterator(f):
def wrapper(*args,**kwargs):
class iterator(object):
def __init__(self,f,args,kwargs):
self.iter = f(*args,**kwargs)
self.lock = threading.RLock()
def __iter__(self):
return self
def next(self):
self.lock.acquire()
try:
return self.iter.next()
finally:
self.lock.release()
return iterator(f,args,kwargs)
return wrapper
@synchronized_iterator
def create_counter():
t = itertools.count()
while True:
yield t.next()
or
counter = synchronized_iterator(itertools.count)
I used a class-based approach, as I don't want to destroy the semantics of
calling the returned wrapper(), which should've already instantiated the
wrapped generator object (which doesn't happen when making wrapper() a
generator itself).
--
--- Heiko.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050403/79c8f09b/attachment.sig>
More information about the Python-list
mailing list