1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
from beaker.util import SyncDict, WeakValuedRegistry
import random, time, weakref
import threading
class Value(object):
values = {}
def do_something(self, id):
Value.values[id] = self
def stop_doing_something(self, id):
del Value.values[id]
mutex = threading.Lock()
def create(id):
assert not Value.values, "values still remain"
global totalcreates
totalcreates += 1
return Value()
def threadtest(s, id):
print("create thread %d starting" % id)
global running
global totalgets
while running:
try:
value = s.get('test', lambda: create(id))
value.do_something(id)
except Exception as e:
print("Error", e)
running = False
break
else:
totalgets += 1
time.sleep(random.random() * .01)
value.stop_doing_something(id)
del value
time.sleep(random.random() * .01)
def runtest(s):
global values
values = {}
global totalcreates
totalcreates = 0
global totalgets
totalgets = 0
global running
running = True
threads = []
for id_ in range(1, 20):
t = threading.Thread(target=threadtest, args=(s, id_))
t.start()
threads.append(t)
for i in range(0, 10):
if not running:
break
time.sleep(1)
failed = not running
running = False
for t in threads:
t.join()
assert not failed, "test failed"
print("total object creates %d" % totalcreates)
print("total object gets %d" % totalgets)
def test_dict():
# normal dictionary test, where we will remove the value
# periodically. the number of creates should be equal to
# the number of removes plus one.
print("\ntesting with normal dict")
runtest(SyncDict())
def test_weakdict():
print("\ntesting with weak dict")
runtest(WeakValuedRegistry())
|