-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththread_safe_list.py
More file actions
63 lines (53 loc) · 1.61 KB
/
thread_safe_list.py
File metadata and controls
63 lines (53 loc) · 1.61 KB
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
import threading
import unittest
class ThreadSafeList():
def __init__(self):
self.list = []
self.lock = threading.Lock()
def append(self, element):
self.lock.acquire()
self.list.append(element)
self.lock.release()
def extend(self, elements):
self.lock.acquire()
self.list.extend(elements)
self.lock.release()
def rotate(self):
self.lock.acquire()
ret = self.list.pop()
self.list.insert(0, ret)
self.lock.release()
return ret
def clear(self):
self.lock.acquire()
self.list.clear()
self.lock.release()
class TestThreadSafeList(unittest.TestCase):
def test_empty(self):
a = ThreadSafeList()
self.assertEqual(len(a.list), 0)
self.assertEqual(a.list, [])
def test_append(self):
a = ThreadSafeList()
a.append('foo')
self.assertEqual(len(a.list), 1)
self.assertEqual(a.list, ['foo'])
def test_extend(self):
a = ThreadSafeList()
a.extend(['foo', 'bar'])
self.assertEqual(len(a.list), 2)
self.assertEqual(a.list, ['foo', 'bar'])
def test_rotate(self):
a = ThreadSafeList()
a.extend(['foo', 'bar'])
r = a.rotate()
self.assertEqual(r, 'bar')
self.assertEqual(a.list, ['bar', 'foo'])
def test_clear(self):
a = ThreadSafeList()
a.extend(['foo', 'bar'])
self.assertEqual(len(a.list), 2)
self.assertEqual(a.list, ['foo', 'bar'])
a.clear()
self.assertEqual(len(a.list), 0)
self.assertEqual(a.list, [])