Creating a safe counter with Python for Zope
Morten W. Petersen
morten at esol.no
Sat Feb 3 13:19:48 EST 2001
Hi guys,
I've been contemplating to create a safe counter for Zope
using Python. I've tried using the FSCounter product
(available from zope.org), but that occassionally
barfs up an Exception.
Now, the problem is that I don't really know too much
about threads and semaphores (which I'm assuming is
the best/easiest way to do it), much less how to make
this work safely with Zope (the ZODB).
This counter is going to be used as a system wide
unique identifier, and it therefore needs to be
completely safe and also persistent.
I've built a simple counter without persistence that
seems to work:
"""
import thread
import threading
import time
class test_counter:
def __init__(self, start=0):
self.counter = start
self.lock = thread.allocate_lock()
def __call__(self):
self.lock.acquire()
counter = self.counter = self.counter + 1
self.lock.release()
return counter
get_unique_id = test_counter()
id_list = []
def crack_it():
while 1:
id_list.append(get_unique_id())
time.sleep(0.01)
threading._start_new_thread(crack_it, ())
threading._start_new_thread(crack_it, ())
threading._start_new_thread(crack_it, ())
threading._start_new_thread(crack_it, ())
"""
And I've run tests on this that append around 100000
integers to the list, all unique.
Now, with this working, can I be sure that if it
subclasses the persistence machinery that it will
always be unique? And that multiple threads or
whatever can't modify it at the same time and
screw up the uniqueness of the value?..
Thank you for your time.
-Morten
More information about the Python-list
mailing list