python - 我写了一个 LockedList 装饰器。我该如何测试它?
问题描述
from threading import Lock
from threading import Thread
class LockedList(list):
def __init__(self, *args, **kwargs):
self._lock = Lock()
super(LockedList, self).__init__(*args, **kwargs)
def remove(self, elem):
with self._lock:
super(LockedList, self).remove(elem)
def insert(self, i, elem):
with self._lock:
super(LockedList, self).insert(i, elem)
def __contains__(self, elem):
with self._lock:
super(LockedList, self).__contains__(elem)
list = [2, 3, 4]
for i in range(100):
t1 = threading.Thread(target=list.insert(i, i))
if i % 2 == 0:
t2 = threading.Thread(target=list.remove(i))
#10 output
for i in range(len(list)):
if i % 10 == 0 and i != 0:
print()
print(list[i], end=' ')
我为使用locked_list 装饰器编写了这段代码。但我不知道如何测试它。测试代码是否正确?我想通过使用线程来测试 list.insert() 和 list.remove() 是否会导致竞争条件。