-
Notifications
You must be signed in to change notification settings - Fork 0
/
safe_list.py
63 lines (57 loc) · 1.4 KB
/
safe_list.py
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
from threading import Lock
# Thread-safe, non-duplicates list.
class SafeList():
def __init__(self):
self.lock = Lock()
self.data = []
# Check if val is in `self.data`
def contains(self, val):
ret = False
self.lock.acquire()
if val in self.data:
ret = True
self.lock.release()
return ret
# Insert val in `self.data`, if not already there
def put(self, val):
self.lock.acquire()
ret = True
if val in self.data:
ret = False
self.lock.release()
return ret
self.data.append(val)
self.lock.release()
return True
# Remove val from `self.data`, if not already there
def take(self, val):
if not self.contains(val):
return False
self.lock.acquire()
self.data.remove(val)
self.lock.release()
return True
# Returns a copy of the current state of `self.data`
def snapshot(self):
ret = []
self.lock.acquire()
for v in self.data:
ret.append(v)
self.lock.release()
return ret
if __name__ == "__main__":
sl = SafeList()
sl.put(2)
sl.put(9)
sl.put(2)
print(sl.contains(2))
print(sl.contains(3))
print(sl.snapshot())
sl.take(2)
sl.take(3)
print(sl.snapshot())
print("""--- Expected: ---
True
False
[2, 9]
[9]""")