1
2
3
4
5
6
7
8
9
10
11
12
13
14 import threading
15 import time
16
18 "Store elements in a map for the given time"
19
24
25
26 - def clean(self, now = None):
27 "remove old values"
28
29 if now is None:
30 now = time.time()
31 if self.lastClean + self.timeout > now:
32 return
33 for k, (v, t) in self.map.items():
34 if t + self.timeout < now:
35 del self.map[k]
36 self.lastClean = now
37
38
39 - def get(self, key, default):
46
47
55
56
61
62
68
69
71 "Use a simple lock for all read/write access to a map"
72
74 self.map = map
75 self.lock = threading.Lock()
76
77
78 - def impl(self, m, *args, **kw):
79 "call a method on the map, with the lock held"
80 self.lock.acquire()
81 try:
82 return m(*args, **kw)
83 finally:
84 self.lock.release()
85
86
89
90
91 - def get(self, *args, **kw):
92 return self.impl(self.map.get, *args, **kw)
93
94
97
98
101
102
103 - def update(self, *args, **kw):
104 return self.impl(self.map.update, *args, **kw)
105